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