From marc.wyburn at googlemail.com Tue Nov 7 09:27:28 2006 From: marc.wyburn at googlemail.com (marc.wyburn at googlemail.com) Date: 7 Nov 2006 06:27:28 -0800 Subject: sound processing modules in python - anyone? In-Reply-To: References: Message-ID: <1162909648.042525.172190@i42g2000cwa.googlegroups.com> I've had a brief look at this and there isn't a sound orientated library as such. You can however use numpy to do stuff like FFTs and there are there is a wave module in python that will allow you to create wavs, you can google for importing wav's into numpy arrays. This seemed like a good idea to me as I think Numpy is written in C or C++ (or maybe it was fortran). There seem to be a lot of people using numpy in a similar way to matlab so there is a fair ammount of the standard DSP routines have already been written. sittner at lkb.ens.fr wrote: > Hi everyone, > I'm looking for a module for sound processing (manipulating sound objets, > filters, ffts etc.). > I tried Snack, but when i downloaded the package that was supposed to be > for python, there was only the Tk/Tcl stuff (where's the .py ?). > could anyone help me with that (or with any other sound module for python)? > thanks in advance, > g From fredrik at pythonware.com Sat Nov 11 18:14:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Nov 2006 00:14:37 +0100 Subject: reduce to be removed? In-Reply-To: <1163285443.536672.289940@m73g2000cwd.googlegroups.com> References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> Message-ID: Dustan wrote: > It's always nice to know there are such good-natured people ready to > help on this group. any special reason why you keep pretending that some random wikipedia editor knows more about a future Python release than the people that develops Python ? > Anyway, I figured out a way to get the builtin > function 'sum' to work as I need: > sum([[1,2,3],[4,5,6],[7,8,9]], []) sum() is designed for adding numbers, not sequences. abusing it for sequences leads to inefficient code, and extremely bad worst- case behaviour, since you end up copying the same data over and over and over again -- the function even checks for strings for this very reason: >>> sum(["123", "456", "789"], "") Traceback (most recent call last): File "", line 1, in ? TypeError: sum() can't sum strings [use ''.join(seq) instead] (maybe it should check for other well-known containers as well?) if you care about writing robust code, why not just use a for-loop, and the list extend method? From cameron.walsh at gmail.com Wed Nov 8 21:37:04 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Thu, 09 Nov 2006 10:37:04 +0800 Subject: Python to tell what is the IP of my PC . In-Reply-To: References: <9afea2ac0611081600r7b2deb49pde0a6477bab7c7ca@mail.gmail.com> <7d2580610611081618g69db3e25k6d21cd6d1f15d8a7@mail.gmail.com> Message-ID: Gabriel Genellina wrote: > At Wednesday 8/11/2006 21:18, Nicolas G wrote: > >> > How can I use python to get the real IP address of my DSL router (when >> > my PC is part of the local home LAN) ? >> >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/162994 >> >> >> import >> win32api raise the error "module not exsit" http://sourceforge.net/projects/pywin32/ >> and >> socket.gethostbyname(name)the router doesn't have a hostname. use the hostname you create on noip.com or dyndns.com etc. Cameron. From erinhouston at gmail.com Sun Nov 5 02:40:10 2006 From: erinhouston at gmail.com (ina) Date: 4 Nov 2006 23:40:10 -0800 Subject: WebScraping In-Reply-To: <454d0fb1$0$11970$afc38c87@news.optusnet.com.au> References: <454d0fb1$0$11970$afc38c87@news.optusnet.com.au> Message-ID: <1162712409.970901.159970@b28g2000cwb.googlegroups.com> This might be of help to you. http://phlik.ishpeck.net/index.php?P=a1141076600phlik http://phlik.ishpeck.net/index.php?P=b1134168973phlik Graham Feeley wrote: > Can someone steer me to scripts / modules etc on webscraping please??? > Ultimately I would like someone to write a script for me. > However i am still searching for documentation on this subject > Thanks Graham From michael at stroeder.com Mon Nov 6 18:47:32 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 07 Nov 2006 00:47:32 +0100 Subject: python-ldap/win32 or python/ldap/win32 In-Reply-To: <1162852448.012799.208740@b28g2000cwb.googlegroups.com> References: <1162852448.012799.208740@b28g2000cwb.googlegroups.com> Message-ID: rcmn wrote: > i'm running around in circle trying to to use python/ldap/ on > win32(WinXP). Maybe this message sent to the python-ldap-dev mailing list helps. You're welcome to follow up on this list. Ciao, Michael. -------- Original Message -------- Subject: Experimental 2.2.0 Windows Build Date: Mon, 4 Sep 2006 22:58:26 -0300 From: Sidnei da Silva To: python-ldap-dev at lists.sourceforge.net Hello there, I've managed to put together an experimental 2.2.0 build for Windows, which can be found here: http://awkly.org/files/python-ldap-2.2.0.win32-py2.4.exe I'm admittedly not an expert in compiling stuff, so if anyone with more expertise can double-check what I've did: http://awkly.org/archive/compiling-python-extensions-on-mingw/ ... specially the change from '-shared' to '-mdll -static' on the arguments to 'ld', I would really *really* appreciate. For the brave folks willing to try out the installer itself, you're at your own risk, but please report back any issues. If the build turns out to work fine and people are willing to bless this as the official Windows build and upload it to sourceforge I would be more than glad. It was built with mingw against: openldap-2.2.29 openssl-0.9.8b -- Sidnei da Silva From p.lavarre at ieee.org Fri Nov 10 10:17:55 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 10 Nov 2006 07:17:55 -0800 Subject: to Doctest as SystemExit is to Python References: <1163136324.202924.165630@k70g2000cwa.googlegroups.com> Message-ID: <1163171875.151236.226850@i42g2000cwa.googlegroups.com> (((I thought I had sent this reply already, Google says No.))) > > Can I somehow tell doctest that it's time to quit? > > ... doctest redefines ... SystemExit ... > > Hit Ctrl-C. Or raise a KeyboardInterrupt: Yes! Thank you!!! I see now, Doctest exactly reverses the python -i experience: doctest exits quietly if I raise KeyboardInterrupt. doctest catches SystemExit and prints the traceback. python -i exits quietly if I raise SystemExit. python -i catches KeyboardInterrupt and prints the traceback. Of course, to make the doctest work as sketched, I had to strip the trailing blanks that my browser introduced and I had to expect tracebacks for raise Exception and raise SystemExit, e.g.: >>> import sys >>> sys.exit() Traceback (most recent call last): ... SystemExit >>> From DustanGroups at gmail.com Sat Nov 11 20:42:32 2006 From: DustanGroups at gmail.com (Dustan) Date: 11 Nov 2006 17:42:32 -0800 Subject: reduce to be removed? In-Reply-To: References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163288885.884417.218270@f16g2000cwb.googlegroups.com> <1163290526.013063.245130@m7g2000cwm.googlegroups.com> Message-ID: <1163295752.701124.322620@h54g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Dustan wrote: > > >> > Because I'm embedding this expression in a list comprehension > >> > >> because? > > > > Because I thought I would be able to get an answer without revealing > > the exact details of what I am doing. > > alright, let's try again: why do you need a self-contained reduce > replacement that can be embedded inside a list comprehension ? > > >>> foo =\ [[[1,2,3],[4,5,6],[7,8,9]], [[3,2,1],[6,5,4],[9,8,7]]] Here, foo appears to be a 3-dimensional list - except it's supposed to be 2-dimensional. The inner-list-of-lists is a result of how I'm producing the data, and now I want to do a mass-concatenation (or extending) of the inner-list-of-lists, and come up with this result: >>> foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]] True What's the best way to accomplish this? It's not quite this simple, but let's just see what you can come up with the information at hand, and I'll see if I can adapt it to my needs. From Leo.Kislov at gmail.com Fri Nov 17 05:30:35 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 17 Nov 2006 02:30:35 -0800 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? References: <455CED78.1060604@v.loewis.de> <455CF4BA.1050608@v.loewis.de> Message-ID: <1163759435.551233.76030@j44g2000cwa.googlegroups.com> Martin v. L?wis wrote: > gabor schrieb: > >> All this code will typically work just fine with the current behavior, > >> so people typically don't see any problem. > >> > > > > i am sorry, but it will not work. actually this is exactly what i did, > > and it did not work. it dies in the os.path.join call, where file_name > > is converted into unicode. and python uses 'ascii' as the charset in > > such cases. but, because listdir already failed to decode the file_name > > with the filesystem-encoding, it usually also fails when tried with > > 'ascii'. > > Ah, right. So yes, it will typically fail immediately - just as you > wanted it to do, anyway; the advantage with this failure is that you > can also find out what specific file name is causing the problem > (whereas when listdir failed completely, you could not easily find > out the cause of the failure). > > How would you propose listdir should behave? How about returning two lists, first list contains unicode names, the second list contains undecodable names: files, troublesome = os.listdir(separate_errors=True) and make separate_errors=True by default in python 3.0 ? -- Leo From vdicarlo at gmail.com Fri Nov 10 10:05:03 2006 From: vdicarlo at gmail.com (vdicarlo) Date: 10 Nov 2006 07:05:03 -0800 Subject: How to choose the right GUI toolkit ? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> Message-ID: <1163171103.549085.108610@m7g2000cwm.googlegroups.com> > I highly recommend wxPython. It's very mature, full-featured, and > portable, and fairly easy to learn as well. I am also a Python beginner thinking about what GUI toolkit to use, and the availability of a free video screencast series on installing and using wxpython at showmedo.com is making me want to go that way. I viewed their introduction to Python resources and wished I had found it first. The wxpython series is at http://tinyurl.com/yggean Vincent From jmdeschamps at gmail.com Thu Nov 9 03:29:46 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 9 Nov 2006 00:29:46 -0800 Subject: Problem getting a file pathname with tkFileDialog In-Reply-To: References: <1163012468.055428.124690@h48g2000cwc.googlegroups.com> <1163016063.961485.224390@k70g2000cwa.googlegroups.com> Message-ID: <1163060986.314142.22060@k70g2000cwa.googlegroups.com> Tim Daneliuk wrote: > Sefyroth wrote: > > Thanks, > > > > but I get this error when I try this. > > > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in > > position 12: ordinal not in range(128) > > > > I had encountered it with the askdirectory method as well. Is there an > > easy way to bypass this? > > > > Thanks again > > I believe you are running into a directory or file name that has > non-ascii characters in it. Python as shipped is set up to > deal with ascii as its native encoding format. You can change > this by editing the "site.py" file - look in the Lib directory > in your python installation. Look for this code: > > ------------------------------- > def setencoding(): > """Set the string encoding used by the Unicode implementation. The > default is 'ascii', but if you're willing to experiment, you can > change this.""" > encoding = "ascii" # Default value set by _PyUnicode_Init() > if 0: > # Enable to support locale aware default string encodings. > import locale > loc = locale.getdefaultlocale() > if loc[1]: > encoding = loc[1] > ------------------------------- > > > > Change the "if 0:" to "if 1:" and see if that doesn't fix the problem. > > > > -- > ---------------------------------------------------------------------------- > Tim Daneliuk tundra at tundraware.com > PGP Key: http://www.tundraware.com/PGP/ you could also use encode("iso-8859-1") to nterpret just the printed name such as: print myfilename.encode("iso-8859-1") and by the way if you wanted the file NAME you could have used openfilename() instead of openfile() ;-) jean-marc From sjmachin at lexicon.net Mon Nov 6 18:07:57 2006 From: sjmachin at lexicon.net (John Machin) Date: 6 Nov 2006 15:07:57 -0800 Subject: Unicode/ascii encoding nightmare In-Reply-To: <454fa3c9$0$13767$4fafbaef@reader3.news.tin.it> References: <1162842650.780517.180360@b28g2000cwb.googlegroups.com> <1162846564.782883.259110@h54g2000cwb.googlegroups.com> <454fa3c9$0$13767$4fafbaef@reader3.news.tin.it> Message-ID: <1162854476.903789.5550@b28g2000cwb.googlegroups.com> Andrea Griffini wrote: > John Machin wrote: > > > The fact that C3 and C2 are both present, plus the fact that one > > non-ASCII byte has morphoploded into 4 bytes indicate a double whammy. > > Indeed... > > >>> x = u"f?dselsdag" > >>> x.encode('utf-8').decode('iso-8859-1').encode('utf-8') > 'f\xc3\x83\xc2\xb8dselsdag' > Indeed yourself. Have you ever considered reading posts in chronological order, or reading all posts in a thread? It might help you avoid writing posts with non-zero information content. Cheers, John From rupole at hotmail.com Wed Nov 8 08:42:55 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 8 Nov 2006 08:42:55 -0500 Subject: More elegant way to obtain ACLs / permissions for windows directories than using "cacls" dos command? References: <1162933222.244854.135180@f16g2000cwb.googlegroups.com> <1162952479_41619@sp6iad.superfeed.net> <1162988020.060319.124030@b28g2000cwb.googlegroups.com> <1162988715.639810.125270@f16g2000cwb.googlegroups.com> Message-ID: <1162993589_43917@sp6iad.superfeed.net> dananrg at yahoo.com wrote: > Could you give an example for listing security descriptors using the > win32security module? I looked at the documentation but found it > confusing. Thanks. There are some examples of using the security descriptor objects in \Lib\site-packages\win32\Demos\security. Also, searching the Python-win32 mailing list should turn up some more code. Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From antoine at vo.lu Tue Nov 7 12:38:17 2006 From: antoine at vo.lu (Antoine De Groote) Date: Tue, 07 Nov 2006 18:38:17 +0100 Subject: shutil: permission denied errors on windows In-Reply-To: <1162919896.527769.38750@m73g2000cwd.googlegroups.com> References: <31b03$454f63b6$544abc47$26270@news.hispeed.ch> <1162858987.931532.61530@h48g2000cwc.googlegroups.com> <1162919896.527769.38750@m73g2000cwd.googlegroups.com> Message-ID: <3931e$4550c48b$544abc47$5625@news.hispeed.ch> Yes, that's exactly what was the case... But see my other post, that straightens things up... Thanks! antoine John Henry wrote: > Okay, it's always good that strange things are repeatable and happens > with simple scripts. > > Are you saying "a" is a folder? So, the failure is only with copying > folder? Not individual file? > > > > Antoine De Groote wrote: >> Yes it's strange, I never had the problem before, either. It seems now >> to be only the case for folders. A very simple >> >> shutil.copy('a', 'b') >> >> already fails with the error message. >> >> I reinstalled Python, but that didn't change anything... >> >> Regards, >> antoine >> >> John Henry wrote: >>> I use the copy function a lot and never have problem. I suggest that >>> you write a no brainer standalone test code and if it still fails >>> there, then you have a problem with your installation. >>> >>> Antoine De Groote wrote: >>>> Google tells quite some things about it, but none of them are satisfactory. >>>> >>>> I'm on Windows, and shutil operations (e.g. move, copy) throw [Errno 13] >>>> Permission denied all the time, for the source files. It seems that this >>>> is the case for all my files. But what I don't understand is that >>>> yesterday it still worked. I didn't change anything on my system though >>>> (at least not that I am aware of). I restarted the computer several >>>> times to see if that helped, but it didn't. Also I can't find a process >>>> that would be using the files... >>>> >>>> Has anybody experienced this problem before, or have a solution? >>>> >>>> Kind regards, >>>> antoine >>>> >>>> Here's the code that throws the errors >>>> >>>> [...] >>>> for l in files: >>>> from_file = os.path.join(dir, l) >>>> to_file = from_file.replace(tree_top, backup_dir) >>>> try: >>>> if not os.path.exists(to_file): >>>> log('Copying new %s' % from_file) >>>> counter_new += 1 >>>> shutil.copy2(from_file, to_file) >>>> elif int(os.path.getmtime(from_file)) > >>>> int(os.path.getmtime(to_file)): >>>> log('Copying modified %s' % from_file) >>>> counter_mod += 1 >>>> shutil.copy2(from_file, to_file) >>>> elif os.path.getsize(from_file) > os.path.getsize(to_file): >>>> log('Sizes differ, but not rest: Copying %s' % >>>> from_file) >>>> counter_special += 1 >>>> shutil.copy2(from_file, to_file) >>>> elif os.path.getsize(from_file) < os.path.getsize(to_file): >>>> log('Orig file smaller than backup file: Copying >>>> %s' % from_file) >>>> counter_special += 1 >>>> shutil.copy2(to_file, backup_dir+'DIFF_SIZE') >>>> shutil.copy2(from_file, to_file) >>>> else: >>>> #log('not treated: %s' % l) >>>> pass >>>> >>>> except (OSError, IOError), e: >>>> not_accessible += 1 >>>> print e >>>> [...] > From icebergwtf at yahoo.com.cn Wed Nov 1 23:47:48 2006 From: icebergwtf at yahoo.com.cn (Tiefeng Wu) Date: Thu, 2 Nov 2006 12:47:48 +0800 (CST) Subject: Make all files extension lower by a given directory name Message-ID: <20061102044749.57630.qmail@web15006.mail.cnb.yahoo.com> Fredrik Lundh wrote: > that's not how splitext works, though: > > >>> os.path.splitext("FOO.BAR") > ('FOO', '.BAR') > > can you post an example of a filename that misbehaves on your machine? > > To Fredrik Lundh and Tim Chase: My task was read all tga file names and generate a config xml file, then pass this xml file to a utility, but this utillity only read files with extension 'tga' than 'TGA'. I tried name + ext first but I got two dots between them, so I wrote code that way (the strip thing), and it worked. Today it does not work (the strip code cut last character from file name, like you said :) ), and I changed it back, now everything is OK. I really don't know what happened yesterday. Thanks. PS. I have python24, python25, python.NET and IronPython installed on my machine, and .py file associate to python24. ___________________________________________________________ ????????-3.5G???20M??? http://cn.mail.yahoo.com From noah.rawlins at comcast.net Thu Nov 30 21:25:57 2006 From: noah.rawlins at comcast.net (Noah Rawlins) Date: Thu, 30 Nov 2006 21:25:57 -0500 Subject: best way to align words? In-Reply-To: <1164925391.696612.64860@80g2000cwy.googlegroups.com> References: <1164925391.696612.64860@80g2000cwy.googlegroups.com> Message-ID: Robert R. wrote: > Hello, > > i would like to write a piece of code to help me to align some sequence > of words and suggest me the ordered common subwords of them > > s0 = "this is an example of a thing i would like to have".split() > s1 = "another example of something else i would like to have".split() > s2 = 'and this is another " example " but of something ; now i would > still like to have'.split() > ... > alist = (s0, s1, s2) > > result should be : ('example', 'of', 'i', 'would', 'like', 'to', 'have' > > but i do not know how should i start, may be have you a helpful > suggestion? > a trouble i have if when having many different strings my results tend > to be nothing while i still would like to have one of the, or maybe, > all the best matches. > > best. > Your requirements are a little vague... how are these three strings handled? s1 = "hello there dudes" s2 = "dudes hello there" s3 = "there dudes hello" they all share the 3 words, but what order do you want them back? here is a simplistic approach using sets that results in a list of words that are in all strings ordered arbitrarily by their order in the first string ( it also doesn't worry about matches (or lack of) due to punctuation and case and crap like that) >>> strList = [] >>> strList.append('this is an example of a thing i would like to have') >>> strList.append('another example of something else i would like to have') >>> strList.append('and this is another " example " but of something ; now i would still like to have') >>> [word for word in strList[0].split() if word in reduce(lambda x, y: x.intersection(y), [set(str.split()) for str in strList])] ['example', 'of', 'i', 'would', 'like', 'to', 'have'] but you still have issues with mutiple matches and how they are handled etc... noah From DustanGroups at gmail.com Sat Nov 4 11:08:27 2006 From: DustanGroups at gmail.com (Dustan) Date: 4 Nov 2006 08:08:27 -0800 Subject: disabledforeground or similar for Entry (in Tkinter) In-Reply-To: <1162656214.176092.46530@f16g2000cwb.googlegroups.com> References: <1162656214.176092.46530@f16g2000cwb.googlegroups.com> Message-ID: <1162656507.768215.60630@f16g2000cwb.googlegroups.com> Dustan wrote: > Back in this post, I attempted to make a label look like a button: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/a83195d3970a6851/2053cbaec1bc1f19?auth=DQAAAHkAAAAMDAWnhNnzpuKlwOKZUwAGUTtT2Ay-EAB7rCY6SnwfnDzZ98M37bZDW2Is0LrBVrr8XEgPfcuOkiUE-CrSsKbBSX-67voDUXfbATBd0eYNMClezby4EXT2fuLm6f0llJ_xMO8BfkjVho_7CZvlf_9tNGnJixTbq8zr21ODZBhouQ > > Alright, I've learned my lesson - don't use a new widget; modify the > old one. > > Except the Entry widget doesn't have a disabledforeground option. > Neither does the Text widget, but IDLE seems to accomplish making a > disabled Text look the same as an enabled Text in the IDLE Help > section. > > No, foreground (fg) and background (bg) don't make a difference; it > still changes the color of the Entry widget upon disabling. > > There must be something I'm missing here... Yes there is! I assumed that http://www.pythonware.com/library/tkinter/introduction/x4447-options.htm was telling the truth, in that it's not listed there. From scott.daniels at acm.org Thu Nov 2 23:19:31 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 02 Nov 2006 20:19:31 -0800 Subject: Style for modules with lots of constants In-Reply-To: References: Message-ID: <454aba90$1@nntp0.pdx.net> Paul McGuire wrote: > class Constants(object): > pass > > Then I defined the context for my LEFT and RIGHT constants, which are being > created to specify operator associativity, and then my constant fields as > attributes of that object: > > opAssoc = Constants(object) > opAssoc.RIGHT = 0 > opAssoc.LEFT = 1 I like something like: class Constants(object): def __init__(self, **kw): for name, val in kw.iteritems(): setattr(self, name, val) Then: opAssoc = Constants(RIGHT=0, LEFT=1) > In your example, this would look something like: > > fileusage = Constants() > fileusage.Transcript = 1 > fileusage.TextMode = 2 fileusage = Constants(Transcript=1, TextMode=2) filemode = Constants(Read=1, Write=2, Append=4) filemode.WriteAppend = filemode.Write | filemode.Append class Constants then becomes a nice place to define methods to convert values to associated names for debugging and such. --Scott David Daniels scott.daniels at acm.org From no-spam at no-spam-no-spam.invalid Mon Nov 6 09:18:29 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Mon, 06 Nov 2006 15:18:29 +0100 Subject: Erronous "unsupported locale setting" ? In-Reply-To: <1162820153.697175.18190@h54g2000cwb.googlegroups.com> References: <1162820153.697175.18190@h54g2000cwb.googlegroups.com> Message-ID: Leo Kislov wrote: > robert wrote: >> Why can the default locale not be set by its true name? but only by '' ? : > > Probably it is just not implemented. But since locale names are system > specific (For example windows accepts 'ch' as Chinese in Taiwan, where > as IANA > considers it Chamorro) setlocale should probably grow an additional > keyword parameter: setlocale(LC_ALL, iana='de-DE') that'd be another fat database to blow up the python core(s). I just wonder why locale.setlocale(locale.LC_ALL,"de_DE") doesn't accept the name, which >>> locale.getlocale() / getdefaultlocale() ('de_DE', 'cp1252') already deliver ? but only this works >>> locale.setlocale(locale.LC_ALL,'German_Germany.1252') 'German_Germany.1252' But 'German_Germany.1252' you cannot get/guess from any locale.getxxxx function I think ... -robert From __peter__ at web.de Thu Nov 16 03:34:11 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Nov 2006 09:34:11 +0100 Subject: More puzzling behavior while subclassing datetime References: <1163659104.321150.322650@e3g2000cwe.googlegroups.com> Message-ID: insyte at gmail.com wrote: > With assistance from Gabriel and Frederik (and a few old threads in > c.l.p.) I've been making headway on my specialized datetime class. Now > I'm puzzled by behavior I didn't expect while attempting to use some of > the alternate datetime constructors. Specifically, it appears if I > call GeneralizedTime.now() it calls the __new__ method of my class but > treats keyword arguments as if they were positional. > > My class: > > class GeneralizedTime(datetime): > def __new__(cls, time=None, *args, **kwargs): > print time, args, kwargs > if isinstance(time, str): > timeValues, tzOffset = cls.stringToTimeTuple(time) > return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset), > **timeValues) > elif isinstance(time, datetime): > timeValues = time.timetuple()[:6] > tzOffset = time.utcoffset() > return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset), > *timeValues) > elif time is None: > print "Still gotta figure out now to do this one..." > else: > raise Invalidtime(time) > @staticmethod > def stringToTimeTuple(timeString): > ... regex that parses timeString ... > >>>> GeneralizedTime.today() > 2006 (11, 16, 0, 35, 18, 747275, None) {} > Traceback (most recent call last): > File "", line 1, in ? > File "gentime.py", line 106, in __new__ > raise InvalidTime(time) > gentime.InvalidTime: 2006 > > So it appears the time tuple is being passed to > GeneralizedTime.__new__, but the first value is being assigned to the > "time" argument. > > Is this a side effect of how datetime is implemented? Yes. Consider: >>> def today(time=None, *args): ... print "time = ", time, "args = ", args ... >>> today(2006, 11, 16) time = 2006 args = (11, 16) To fix the issue you'll probably have to remove the time=None parameter from GeneralizedTime.__new__() and instead extract it from args or kwargs. Peter From hakonrk at fys.uio.no Sat Nov 11 18:43:33 2006 From: hakonrk at fys.uio.no (Haakon Riiser) Date: Sat, 11 Nov 2006 23:43:33 +0000 (UTC) Subject: httplib continuation packets References: Message-ID: [Fredrik Lundh] > Haakon Riiser wrote: > >> Yes, and it doesn't help. > > then the server is mostly likely broken beyond repair. It's not in my power to upgrade the server, unfortunately. Guess I'll have to use Perl. > to see if this really is the problem, you could try moving the call to > self._send_output() from the end of the endheaders() method to the end > of the _send_request() method (around line 870 in httplib.py, at least > in 2.5). Tried this, but the tcpdump still looks the same (two packets: one with the headers, one with the body), and now it fails with urllib2.HTTPError: HTTP Error 501: Not Implemented Nevertheless, I'm fairly sure that the packet fragmentation is the culprit. It works perfectly with Perl, even when I make no effort at all to spoof the browser (no user-agent, referer, cookies, etc.). -- Haakon From hg at nospam.com Wed Nov 22 13:54:28 2006 From: hg at nospam.com (hg) Date: Wed, 22 Nov 2006 12:54:28 -0600 Subject: utf - string translation In-Reply-To: References: Message-ID: hg wrote: > Fredrik Lundh wrote: >> hg wrote: >> >>> We noticed that len('?') != len('a') >> sounds odd. >> >>>>> len('?') == len('a') >> True >> >> are you perhaps using an UTF-8 editor? >> >> to keep your sanity, no matter what editor you're using, I recommend >> adding a coding directive to the source file, and using *only* Unicode >> string literals for non-ASCII text. >> >> or in other words, put this at the top of your file (where "utf-8" is >> whatever your editor/system is using): >> >> # -*- coding: utf-8 -*- >> >> and use >> >> u'' >> >> for all non-ASCII literals. >> >> >> > > Hi, > > The problem is that: > > # -*- coding: utf-8 -*- > import string > print len('a') > print len('?') > > returns 1 then 2 > > and string.maketrans(str1, str2) requires that len(str1) == len(str2) > > hg > > > > > PS: I'm running this under Idle From shejo284 at gmail.com Tue Nov 7 14:37:32 2006 From: shejo284 at gmail.com (Sheldon) Date: 7 Nov 2006 11:37:32 -0800 Subject: C wrapper Message-ID: <1162928252.643092.23350@h48g2000cwc.googlegroups.com> Hi, Can anyone give me some idea as to what this error means? "ImportError: dynamic module does not define init function " I am new at this and there is still a lot to learn. Any help is appreciated, /Sheldon From inq1ltd at verizon.net Fri Nov 3 10:21:05 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Fri, 03 Nov 2006 10:21:05 -0500 Subject: SE 2.3 temporarily unavailable. Cheese shop defeats upload with erratic behavior. Urgently requesting help. In-Reply-To: <454A4E1D.8030106@vtxmail.ch> References: <4549FA01.4090706@vtxmail.ch> <200611021020.31599.inq1ltd@verizon.net> <454A4E1D.8030106@vtxmail.ch> Message-ID: <200611031021.05186.inq1ltd@verizon.net> On Thursday 02 November 2006 14:59, Frederic Rentsch wrote: > jim-on-linux wrote: > > Frederic, > > > > I've been trying to get back into my package > > in the Cheese Shop for over a year. The phone > > company changed my e:mail address and to make > > a long and frustrating story short I can't > > get back into the Cheese Shop to make changes > > to my file. > > > > Time is money. At some time you have to > > consider if it is worth it. At least you > > have the name of your program listed. > > > > I wish I could be more helpfull. I'll watch > > the responses you get from others. > > > > Good Luck, > > jim-on-linux > > > > http://www.inqvista.com > > > > On Thursday 02 November 2006 09:00, you wrote: > >> Some time ago I had managed to upload a > >> small package to the Cheese Shop using the > >> data entry template. Uploading is in two > >> steps: first the text then the package file. > >> When I had a new version it went like this: > >> The new text made a new page, but the new > >> file went to the old > > > > snip > > Thanks for letting me know that I am not alone. > Do you know of an alternative to the Cheese > Shop? > > Frederic Python registering alternatives? Part of the mission of the Cheese Shop is to safeguard the name of your software. Once registered, no one else can use that name. That's been done, unless you spelled the package name wrong. I read the following, and I'm not sure if you have tried it. The quote below is from: http//:www.python.org/doc/current/dist/package-index.htm item #7 Registering with the Package Index. (11-15-2004) "By default PyPi will list all versions of a given package. To hide certain versions, the hidden property should be set to yes. This must be edited through the web interface." Sounds to me that you can hide what is on the site and submit a new version, if you set "Hidden property" to "yes". I don't know of any other place to register a python package with the python organization. Good Luck, jim-on-linux http://www.inqvista.com From jstroud at mbi.ucla.edu Wed Nov 1 04:34:17 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 01 Nov 2006 09:34:17 GMT Subject: High level csv reader In-Reply-To: <1162361464.706313.221590@e64g2000cwd.googlegroups.com> References: <1162361464.706313.221590@e64g2000cwd.googlegroups.com> Message-ID: George Sakkis wrote: > It occured to me that most times I read a csv file, I'm often doing > from scratch things like assigning labels to columns, mapping fields to > the appropriate type, ignoring some fields, changing their order, etc. > Before I go on and reinvent the wheel, is there a generic high level > wrapper around csv.reader that does all this ? > > Thanks, > George > There is a csv in the standard library. Though many of us don't mind answering questions like this, you can get a lot of answers quicker by (1) looking to see what's in the standard library and (2) using google. http://docs.python.org/lib/module-csv.html James From daniel.dittmar at sap.com Thu Nov 9 12:36:13 2006 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 09 Nov 2006 18:36:13 +0100 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> Message-ID: Michael Hobbs wrote: > But if the BDFL insists that it remains, why not > take the converse approach? That is, assume that the expression ends at > the colon, not at the newline. That would make this type of statement > possible: I suggested something like this a while back. The answer then was that error messages in case of a forgotten colon would be misleading, at the wrong position, or both. Today: if a or b print x File "colontest.py", line 2 if a or b ^ SyntaxError: invalid syntax Daniel From steve at REMOVE.THIS.cybersource.com.au Wed Nov 22 05:18:00 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 22 Nov 2006 21:18:00 +1100 Subject: Is there a list comprehension for this? References: <1164143944.874745.19470@f16g2000cwb.googlegroups.com> <1164171602.525542.56750@f16g2000cwb.googlegroups.com> Message-ID: On Tue, 21 Nov 2006 21:00:02 -0800, John Machin wrote: > Steven D'Aprano wrote: > > [snip] > >> def running_sum(dw): >> """Return a list of the running sums of sequence dw""" >> rs = [0]*len(dw) >> for i in range(len(dw)): >> rs[i] = dw[i] + rs[i-1] > > Please explain to the newbies why there is no exception raised when > rs[i-1] is executed for i == 0, and state whether you consider this is > a Good Idea or a Filthy Trick or a Fortunate Accident. Because rs[0-1] is just rs[-1], which fetches the LAST item of the list. I cunningly initialised the list to all zeroes, so adding zero to the first term doesn't change the result value. It is a variation of the sentinel technique, where you add an extra value to the beginning or end of a list so that you don't need to treat the first or last item differently. In this specific case, I think it is a combination of Good Idea and Fortunate Accident, but since the meaning of list[-1] is both deliberate and well-documented, it is certainly not a Filthy Trick. -- Steven. From jm.suresh at gmail.com Tue Nov 14 01:20:03 2006 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 13 Nov 2006 22:20:03 -0800 Subject: to setattr or def setProp() Message-ID: <1163485203.560900.286430@b28g2000cwb.googlegroups.com> I have a class for rectangle and it has two points in its __slots__ . However, we can derive a number of properties like width, height, centerPoint etc from these two points. Now, I want to be able to set and get these properties directly from the instances. I can either def __setattr__ , __getattr__ or I can define function for each property like setWidth(), setHeight() . Which one would be faster? I would prefer doing through __setattr__, __getattr__ because it makes the code more readable. However, speed is a concern I would have to do these operations in few thousand iterations for about 50-100 rectangles. -- Suresh From dale at riverhall.nospam.co.uk Wed Nov 1 16:11:08 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Wed, 01 Nov 2006 21:11:08 +0000 Subject: Providing full interaction with the run time References: Message-ID: Thanks for the info. I didn't know about that module. I'll take a look. Fredrik Lundh wrote: > Dale Strickland-Clark wrote: > >> We have a system we're developing which runs as a server. It has an >> xml-rpc interface which I've extended to provide some debugging >> facilities. This has already proved very useful and will continue to be >> so as the system is prepared for live deployment. >> >> The debugging interface attempts to emulate the Python interactive shell. >> You type expressions, you get an answer. You type statements, they get >> executed. >> >> The problem is these two types of input are handled differently by >> Python. You don't seem to be able to pass statements (which includes >> assignments) and expressions through the same calls. >> >> There are three keywords that support this type of function: EXEC, EVAL >> and COMPILE. We can ignore EXEC for this because it doesn't support >> saving and restoring a local environment and EVAL can do it better. > > huh? both exec and eval take optional execution contexts: > > http://effbot.org/pyref/eval.htm > http://effbot.org/pyref/exec.htm > >> Or am I going about this all wrong? > > yes, you're trying to reinvent the "code" module (and badly, it seems > ;-). see the library reference to details, this page for some examples: > > http://www.effbot.org/librarybook/code.htm > > -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From mail at microcorp.co.za Sat Nov 11 01:27:49 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 11 Nov 2006 08:27:49 +0200 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> <4rjlkqFrlskqU1@mid.individual.net> <4rk5giFrerjfU1@mid.individual.net> Message-ID: <022001c7055a$b24c7860$03000080@hendrik> "Fredrik Lundh" wrote: 8<--------------------------------------------------- > >>> color = "blue" > >>> if color == "red" or "green" or "yellow": > ... print color, "is red or green or yellow" > ... > blue is red or green or yellow *grin* - this can be construed as a weakness in Python - Even COBOL compilers in the sixties would "add in" the implied "if color = " after each 'or', instead of bloody - mindedly thinking: ok the first condition is not true the second "condition" 's string is not empty, so take the true path... BUT - the other way leads naturally to abominations like: if color not equal to 'red' or 'green' or 'yellow'.... where 'green' and 'yellow' takes the "wrong" path, as neither is equal to red, when what you wanted was: if color not equal to 'red' and 'green' and 'yellow'... Long live de Morgan! In this Python simply requires you to be specific in what you want, which is in a sense a GoodThing, seen as a BadThing by lazy programmers. And as for the colon : colon schmolon - its irrelevant either way, but if the interpreter requires it, you have no choice but to type it... Programming is basically about guessing what was in the mind of the compiler writer. - Hendrik From nejucomo at gmail.com Tue Nov 14 01:58:07 2006 From: nejucomo at gmail.com (nejucomo at gmail.com) Date: 13 Nov 2006 22:58:07 -0800 Subject: A memory leak involving builtin/pure-python inheritance. Message-ID: <1163487487.217023.133530@h48g2000cwc.googlegroups.com> Hi folks, Quick Synopsis: A test script demonstrates a memory leak when I use pythonic extensions of my builtin types, but if I use the builtin types themselves there is no memory leak. If you are interested in how builtin/pure-python inheritance interacts with the gc, maybe you can help me fix my memory leak. Background: I'm creating an extension module (see [1]) which implements the LADSPA host interface (see [2]). A similar project appears to do the same using pyrex (see [3]), but I have not investigated it yet. I've discovered a memory leak and I'm fairly certain of the where the culprit reference cycle is. The problem is I am not sure how to instruct the gc to handle it, even after reading about supporting builtin containers (see [4]). My question: How do I correctly implement a builtin type and its pythonic extension type such that reference cycles are detected and collected? Details: There are three relevant LADSPA types: A "handle" is an audio processing module which operates on input and output streams. A "descriptor" describes the interface to a handle such as the types in the I/O streams, and their names and descriptions. A handle is the instantiation of a particular descriptor. A "plugin" is a container providing zero or more descriptors which can be dynamically loaded. (Typically a shared object library that the LADSPA host loads at runtime.) The python-ladspa package is designed as follows: There is a low-level builtin extension module, called "_ladspa", and a high-level interface module, called "ladspa". For each of the three LADSPA types, there is an extension type in the "_ladpsa" module, for example: "_ladspa.Descriptor". For each extension type there is a high-level subtype in the "ladspa" module. So "ladspa.Handle" inherits from "_ladspa.Handle". The reference structure of the "_ladspa" module is tree-like with no cycles. This is because a handle has a single reference to its descriptor, and a descriptor has a single reference to its plugin. However, the high-level interface introduces a reference cycle because this makes the interface more natural, IMO. I've created a diagram which attempts to represent the inheritance relationships as well as the reference structure of this wrapper (see [5]). Let me know if you find it clarifies things or needs improvement. There is a test script, "memleak.py", which tests either module by repeatedly instantiating and discarding references to handles (see [6]). When configured to use the "_ladspa" module, there appears to be no memory usage growth, but if using the "ladspa" module, memory grows linearly with the number of iterations. If I comment out the "Descriptors" list in the "ladspa.Plugin" class (which removes the reference cycle) then "memleak.py" runs with no apparent memory leak. The leak persists even if I implement traverse and clear methods for all three builtin types, unless I've done this incorrectly. Of course one solution is to do away with the reference cycle. After all the _ladspa extension does not have the cycle and is usable. However I care more about a user-friendly interface (which I believe the reference cycle provides) and also I'm just curious. Thanks for any help, Nejucomo References: [1] http://sourceforge.net/projects/python-ladspa/ [2] http://www.ladspa.org/ [3] http://sourceforge.net/projects/dsptools/ [4] http://www.python.org/doc/2.3.5/ext/node24.html [5] http://python-ladspa.svn.sourceforge.net/viewvc/python-ladspa/doc/refgraph.png?revision=41&view=markup [6] http://python-ladspa.svn.sourceforge.net/viewvc/python-ladspa/test/memleak.py?revision=37&view=markup From DustanGroups at gmail.com Sat Nov 4 11:03:34 2006 From: DustanGroups at gmail.com (Dustan) Date: 4 Nov 2006 08:03:34 -0800 Subject: disabledforeground or similar for Entry (in Tkinter) Message-ID: <1162656214.176092.46530@f16g2000cwb.googlegroups.com> Back in this post, I attempted to make a label look like a button: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a83195d3970a6851/2053cbaec1bc1f19?auth=DQAAAHkAAAAMDAWnhNnzpuKlwOKZUwAGUTtT2Ay-EAB7rCY6SnwfnDzZ98M37bZDW2Is0LrBVrr8XEgPfcuOkiUE-CrSsKbBSX-67voDUXfbATBd0eYNMClezby4EXT2fuLm6f0llJ_xMO8BfkjVho_7CZvlf_9tNGnJixTbq8zr21ODZBhouQ Alright, I've learned my lesson - don't use a new widget; modify the old one. Except the Entry widget doesn't have a disabledforeground option. Neither does the Text widget, but IDLE seems to accomplish making a disabled Text look the same as an enabled Text in the IDLE Help section. No, foreground (fg) and background (bg) don't make a difference; it still changes the color of the Entry widget upon disabling. There must be something I'm missing here... From rpdooling at gmail.com Tue Nov 7 16:37:28 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 7 Nov 2006 13:37:28 -0800 Subject: sqlite query not working In-Reply-To: <4550fa9f$0$17710$c3e8da3@news.astraweb.com> References: <4550f36e$0$8780$c3e8da3@news.astraweb.com> <4550f7a5$0$14445$c3e8da3@news.astraweb.com> <4550fa9f$0$17710$c3e8da3@news.astraweb.com> Message-ID: <1162935448.060121.258780@m7g2000cwm.googlegroups.com> John Salerno wrote: >> Ah well, I'm sure there was *something* different Are you sure that it's not you were doing SELECT before, as opposed to INSERT? rd From roman.yakovenko at gmail.com Wed Nov 29 15:14:02 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Wed, 29 Nov 2006 22:14:02 +0200 Subject: libboost, python, and dijkstra shortest path In-Reply-To: <1164828952.285225.193680@j72g2000cwa.googlegroups.com> References: <1164822664.826189.28760@80g2000cwy.googlegroups.com> <1164828952.285225.193680@j72g2000cwa.googlegroups.com> Message-ID: <7465b6170611291214r623c7845n66a9ac33b91ad488@mail.gmail.com> On 29 Nov 2006 11:35:52 -0800, Bytter wrote: > Ok, found the solution here: http://www.osl.iu.edu/~dgregor/bgl-python/ > > But still cannot make anything that works... Anyone who has experience > in this area can help me with the following code: > > import boost as bgl > > graph = bgl.Graph() > a = graph.add_vertex() > b = graph.add_vertex() > e = graph.add_edge(a, b) > > weights = graph.edge_property_map('integer') > weights[e] = 5 > graph.edge_properties['weight'] = weights > > boost.dijkstra_shortest_paths(graph, a) You'd better ask the question on boost.python or boost-users mailing lists: http://boost.org/more/mailing_lists.htm -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From robert.kern at gmail.com Fri Nov 10 11:00:06 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 10 Nov 2006 10:00:06 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: <17748.35935.368749.950252@montanaro.dyndns.org> References: <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <45538b0d$0$26485$c3e8da3@news.astraweb.com> <17748.35935.368749.950252@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > P.S. I felt I just had to tie this into the thread on profanity somehow. > But notice that I didn't mention nazis or Hitler. ;-) You did it just now! -- 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 monica.medina at ngc.com Fri Nov 3 16:49:12 2006 From: monica.medina at ngc.com (matey) Date: 3 Nov 2006 13:49:12 -0800 Subject: Python and SSL enabled In-Reply-To: <6sKdnXGZ2clC-NTYnZ2dnUVZ_oKdnZ2d@comcast.com> References: <1161711493.617569.178870@h48g2000cwc.googlegroups.com> <1162328451.004606.194700@m7g2000cwm.googlegroups.com> <1162421799.262364.100190@e3g2000cwe.googlegroups.com> <6sKdnXGZ2clC-NTYnZ2dnUVZ_oKdnZ2d@comcast.com> Message-ID: <1162590552.461754.276380@m7g2000cwm.googlegroups.com> It appears my __m2crypto.so didn't get built correctly. ================================================ cengsu01:/home/mmedina/crypt/m2kcrypto/m2crypto-0.16 >python setup.py build /usr/local/lib/python2.3/distutils/extension.py:128: UserWarning: Unknown Extension options: 'swig_opts' warnings.warn(msg) running build running build_py running build_ext building '__m2crypto' extension swig -python -ISWIG -I/home/mmedina/crypt/openssl/openssl-0.9.8/include -o SWIG/_m2crypto.c SWIG/_m2crypto.i gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I/home/mmedina/crypt/m2kcrypto/m2crypto-0.16/SWIG -I/home/mmedina/crypt/openssl/openssl-0.9.8/include -I/usr/local/include/python2.3 -c SWIG/_m2crypto.c -o build/temp.solaris-2.9-sun4u-2.3/SWIG/_m2crypto.o -DTHREADING In file included from /usr/local/include/python2.3/stringobject.h:10, from /usr/local/include/python2.3/Python.h:83, from SWIG/_m2crypto.c:13: /opt/sfw/lib/gcc-lib/sparc-sun-solaris2.9/2.95.3/include/stdarg.h:170: warning: redefinition of `va_list' /usr/include/stdio.h:120: warning: `va_list' previously declared here SWIG/_m2crypto.c:3502: warning: function declaration isn't a prototype SWIG/_m2crypto.c:3666: warning: function declaration isn't a prototype SWIG/_m2crypto.c: In function `make_stack_from_der_sequence': SWIG/_m2crypto.c:3763: warning: function declaration isn't a prototype SWIG/_m2crypto.c: At top level: SWIG/_m2crypto.c:4897: warning: function declaration isn't a prototype SWIG/_m2crypto.c:5589: warning: function declaration isn't a prototype SWIG/_m2crypto.c:6556: warning: function declaration isn't a prototype SWIG/_m2crypto.c:7689: warning: function declaration isn't a prototype SWIG/_m2crypto.c:8111: warning: function declaration isn't a prototype SWIG/_m2crypto.c:8912: warning: function declaration isn't a prototype SWIG/_m2crypto.c:10924: warning: function declaration isn't a prototype SWIG/_m2crypto.c:13654: warning: function declaration isn't a prototype SWIG/_m2crypto.c:15281: warning: function declaration isn't a prototype SWIG/_m2crypto.c:13654: warning: function declaration isn't a prototype SWIG/_m2crypto.c:15281: warning: function declaration isn't a prototype SWIG/_m2crypto.c:15302: warning: function declaration isn't a prototype SWIG/_m2crypto.c:15895: warning: function declaration isn't a prototype SWIG/_m2crypto.c:16086: warning: function declaration isn't a prototype SWIG/_m2crypto.c:559: warning: `SWIG_Python_ConvertPacked' defined but not used warning: no library file corresponding to '/home/mmedina/lib' found (skipping) gcc -shared build/temp.solaris-2.9-sun4u-2.3/SWIG/_m2crypto.o -L/home/mmedina/crypt/openssl/openssl-0.9.8/lib -lssl -lcrypto -o build/lib.solaris-2.9-sun4u-2.3/M2Crypto/__m2crypto.so Text relocation remains referenced against symbol offset in file 0x5c0 /home/mmedina/lib/libssl.a(s3_lib.o) 0x5c4 /home/mmedina/lib/libssl.a(s3_lib.o) 0x5c8 /home/mmedina/lib/libssl.a(s3_lib.o) 0x5cc /home/mmedina/li ======================================================== Not sure what is going on here. Can it not find my libraries? Heikki Toivonen wrote: > matey wrote: > > I tried to run the following simple program.... > > > > #!/usr/local/bin/python > > > > import M2Crypto > > > > u = M2Crypto.m2urllib.URLopener() > > u.open('http://www.yahoo.com') > > > > However I got the following errror: > > > > Traceback (most recent call last): > > File "test.py", line 3, in ? > > import M2Crypto > > File "/home/mmedina/python2.3/site-packages/M2Crypto/__init__.py", > > line 14, in ? > > import __m2crypto > > ImportError: ld.so.1: python: fatal: relocation error: file > > /home/mmedina/python2.3/site-packages/M2Crypto/__m2crypto.so: symbol > > d2i_SSL_SESSION: referenced symbol not found > > cengsu01:/home/mmedina/scripts/python > > > Sorry, no idea why you are getting this. > > Btw, I think even the M2Crypto m2urllib is unsafe, you'd be better of > using some of the other convenience libs libs httpslib or something. > > > However, I went back to INSTALL instructions for m2crytpo. I saw I > > forgot to run alltests.py > > > > I ran the alltests.py and received the following: > > > > Traceback (most recent call last): > > ImportError: No module named __m2crypto > > Currently you need to install M2Crypto before you can run the tests. > Next version of M2Crypto will have an option to run tests without > installing. I'd assume if copied the sources to your own site-packages > dir and set the PYTHONPATH environment variable this would have worked. > Notice that you'd need to copy the *built* M2Crypto dir, not the source > M2Crypto dir which does not include the .so file. > > -- > Heikki Toivonen From fredrik at pythonware.com Fri Nov 17 03:43:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 17 Nov 2006 09:43:39 +0100 Subject: Secure Python In-Reply-To: References: <455c1665@quokka.wn.com.au><455c4d9b@quokka.wn.com.au> Message-ID: Stephan Kuhagen wrote: > Never heard about it, maybe it's worth a look for the OP. $ more Misc/HISTORY ... What's New in Python 2.3 alpha 2? ================================= *Release date: 19-Feb-2003* ... - Bastion.py and rexec.py are disabled. These modules are not safe in Python 2.2 or 2.3. historical references: http://effbot.org/librarybook/rexec.htm http://effbot.org/librarybook/bastion.htm From david at boddie.org.uk Mon Nov 6 11:58:57 2006 From: david at boddie.org.uk (David Boddie) Date: 6 Nov 2006 08:58:57 -0800 Subject: Really strange behavior References: Message-ID: <1162832336.928797.235190@h48g2000cwc.googlegroups.com> Sion Arrowsmith wrote: > I don't know if this is the problem or not (knowing neither Qt nor > Twisted), but creWin() creates a window (or two) then throws it > (them?) away on returning to main() (I assume you've chopped > off the bit where main() is actually called). So it's not too > surprising your window doesn't show: by the time you get to > running anything, you don't have a window object to show. It seems to me that your analysis is correct. The first example works as expected because MainWindow is still in scope when the reactor is run. def main(): app = QtGui.QApplication(sys.argv) qt4reactor.install(app) MainWindow = QtGui.QMainWindow() win = Window(MainWindow) MainWindow.show() from twisted.internet import reactor reactor.run() However, in the second example, MainWindow is created as a local variable inside creWin() and is deleted when that function returns. def creWin(): MainWindow = QtGui.QMainWindow() win = Window(MainWindow) MainWindow.show() def main(): app = creApp() creWin() from twisted.internet import reactor reactor.run() By the time the reactor runs, there's no window (open or otherwise) so the application will never exit the Qt event loop (or whatever actually runs when Twisted is involved). > (Unless a Qt application object is a discoverable global and > windows inject a reference to themselves into it.) Well, you can access the application's instance, once it's been set up, via the qApp global variable in the PyQt4.QtGui module. However, you can't take advantage of Qt's parent-based object ownership mechanism to get round this issue with local variables because widgets need to be given QWidget parents, and QApplication is not a QWidget subclass. The original poster should either use a global MainWindow variable or encapsulate the functions in a class. David From DustanGroups at gmail.com Sat Nov 11 21:19:36 2006 From: DustanGroups at gmail.com (Dustan) Date: 11 Nov 2006 18:19:36 -0800 Subject: reduce to be removed? In-Reply-To: References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163288885.884417.218270@f16g2000cwb.googlegroups.com> Message-ID: <1163297976.786873.124350@m73g2000cwd.googlegroups.com> Robert Kern wrote: > Dustan wrote: > > Fredrik Lundh wrote: > > >> if you care about writing robust code, why not just use a for-loop, > >> and the list extend method? > > > > Because I'm embedding this expression in a list comprehension (as I > > stated in my original post), and last time I checked, it's not possible > > to treat a for-loop as an expression (which is what a list > > comprehension requires). > > As with all such things, you stick the implementation in a well-named function > and simply call the function everywhere. The implementation never needs to be a > one-liner expression. It's already in a function, but in order to convert the reduce function into a for-loop that I can use as an expression, I would have to create another independent function, which would make that code more cluttered than it already is. Unless you're saying to perform the list comprehension manually. That would be two for-loops I use in the list comprehension, plus another one to take place of the reduce function. Sure, that spreads out each individual step a little more, but it also makes it more difficult to understand what the overall goal of the code is (I'm going for readability as well as easy maintenance here). > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From DustanGroups at gmail.com Sat Nov 11 17:50:43 2006 From: DustanGroups at gmail.com (Dustan) Date: 11 Nov 2006 14:50:43 -0800 Subject: reduce to be removed? In-Reply-To: References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> Message-ID: <1163285443.536672.289940@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > Dustan wrote: > > > What's an accumulation loop, and how would I convert this code so it's > > compatible with the future 3.0 > > the release of Python 3.0 is far away, and nobody knows how it's going > to look. trying to be future-compatible at this time is a major waste > of time and (not quite as wasteful as reopening yet another old "let's > make some pointless change to the language" thread, but almost). > > surely you must have something better to do with your time ? > > It's always nice to know there are such good-natured people ready to help on this group. Anyway, I figured out a way to get the builtin function 'sum' to work as I need: sum([[1,2,3],[4,5,6],[7,8,9]], []) On an unrelated note, can anyone explain this unpredictable behavior on IDLE? I swear I never hit ctrl-c... ============================== >>> help(sum) Help on built-in function sum in module __builtin__: sum(...) sum(sequence, start=0) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start'. When the sequence is empty, returns start. Traceback (most recent call last): File "", line 1, in help(sum) File "C:\Python25\lib\site.py", line 346, in __call__ return pydoc.help(*args, **kwds) File "C:\Python25\lib\pydoc.py", line 1642, in __call__ self.help(request) File "C:\Python25\lib\pydoc.py", line 1687, in help self.output.write('\n') File "C:\Python25\lib\idlelib\PyShell.py", line 1246, in write self.shell.write(s, self.tags) File "C:\Python25\lib\idlelib\PyShell.py", line 1235, in write raise KeyboardInterrupt KeyboardInterrupt ============================== From tim at tdw.net Thu Nov 23 10:04:20 2006 From: tim at tdw.net (Tim Williams) Date: Thu, 23 Nov 2006 15:04:20 +0000 Subject: "10, 20, 30" to [10, 20, 30] In-Reply-To: References: <1164280390.745628.167770@k70g2000cwa.googlegroups.com> <9afea2ac0611230335r7c987fcdw9918ef55746afe96@mail.gmail.com> Message-ID: <9afea2ac0611230704t536e7631w80a27ee30bc7a2d@mail.gmail.com> On 23/11/06, Fredrik Lundh wrote: > Tim Williams wrote: > >>>> > > and the use of a list comprehension is pretty silly to, given that you want > to apply the same *function* to all items, and don't really need to look > it up for every item: > > map(int, s.split(',')) Haha, thanks Frederic, I wondered how long it would take for a reply from you :) "Silly" though ?? Tim :) From antonioskatsikadamos at yahoo.com Wed Nov 8 09:26:17 2006 From: antonioskatsikadamos at yahoo.com (Antonios Katsikadamos) Date: Wed, 8 Nov 2006 06:26:17 -0800 (PST) Subject: python Error: IndentationError: expected an indented block Message-ID: <20061108142618.77660.qmail@web58114.mail.re3.yahoo.com> hi all. I am using python 2.4. I have to run an older python code and when i run it i get the following message IndentationError: expected an indented block. 1)what does this mean? 2)how can i overcome this problem Thanks for any advice. kind regards, Antonios --------------------------------- Sponsored Link Free Uniden 5.8GHz Phone System with Packet8 Internet Phone Service -------------- next part -------------- An HTML attachment was scrubbed... URL: From dlenski at gmail.com Wed Nov 15 19:46:14 2006 From: dlenski at gmail.com (Dan Lenski) Date: 15 Nov 2006 16:46:14 -0800 Subject: Will GPL Java eat into Python marketshare? In-Reply-To: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> References: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> Message-ID: <1163637974.453889.17100@h54g2000cwb.googlegroups.com> walterbyrd wrote: > Some think it will. > > Up untill now, Java has never been standard across different versions > of Linux and Unix. Some think that is one reason that some developers > have avoided Java in favor of Python. Now that Java has been GPL'd that > might change. > > IMO: it won't make much difference. But I don't really know. I don't think so. Java and Python don't really belong to the same "class" of programming languages: C++, Java: strongly typed, statically typed object-oriented programming languages... minimal runtime means that these languages can be compiled to native executables easily (yes, Java can now with things like GCJ and appropriate libraries) Python, Perl, Ruby: dynamically typed object-oriented programming languages... lots of runtime intelligence allows you to do things like create a new class or function at runtime, or look up a symbol based on a string of its name, or execute a string containing source code (these things make the language more flexible but pretty hard to compile to native code without embedding an interpreter) The "mindset" required to program effectively in C++ or Java is very different from that required to program effectively in Python or Perl, in a way that's quite separate from the syntactical distinctions between these languages... I think most programmers settle comfortably into one mindset that fits best with the tasks they do, and try not to move outside of it. The ranks of C++ programmers have already been diminished by many of them jumping to Java, since it offers less complex syntax and better cross-platform support. I expect that GPL'ed Java will accelerate the decline of C++. But I don't see Java competing directly with Python... Dan From paul.keating at nibc.com Fri Nov 10 10:13:33 2006 From: paul.keating at nibc.com (paul.keating at nibc.com) Date: 10 Nov 2006 07:13:33 -0800 Subject: newbee I have an object how to check what's his class? In-Reply-To: References: Message-ID: <1163171613.040825.78290@m73g2000cwd.googlegroups.com> This doesn't answer your whole post because it asked a lot of questions. But as to finding out whether something is an instance of a class: class X(object): # ... defined as in your post >>> x = X('Fred') >>> x class X contains: >>> type(x) is X True >>> isinstance(x,X) True >>> x.__class__.__name__ 'X' Now for subclasses: class Y(X): extrastuffinY = 1 >>> y = Y('Joe') >>> type(y) is X False >>> isinstance(y,X) True consternation: > I can't find neither in tutorial nor with google It's all about > isinstance, or __class__. > How to test that an object is an instance of my X class?? From deets at nospam.web.de Thu Nov 2 06:27:54 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 02 Nov 2006 12:27:54 +0100 Subject: other ways to check for ? In-Reply-To: References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> Message-ID: <4qu31oFobjovU1@uni-berlin.de> Sybren Stuvel schrieb: > elderic enlightened us with: >> are there other ways than the ones below to check for > 'function'> in a python script? > > First of all, why would you want to? If you want to call the object > as a function, just do so. Handle the exception that is raised when > it's raised. That's an advice I've heard a few times to often. I'm totally buying duck-typing. Yet the advice of simply calling a function to determine that it is one isn't sound in a lot of cases where you want to use it as callback later on. E.g. the turbogears DataGrid can get either a string or a callable passed as column-data-provider. But which of these two options is used must be known at construction time, not at later calling time. Diez From jeremy+complangpython at jeremysanders.net Tue Nov 7 05:34:23 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 07 Nov 2006 10:34:23 +0000 Subject: Plot pkg - Multiple Y axes? References: <1162836527.115500.46420@i42g2000cwa.googlegroups.com> Message-ID: monkeyboy wrote: > I'm searching for a plotting package that will allow multiple y axes of > different scales. For example I'd like to overlay 4 or 5 time series > with each series having a separate axis. Does anyone know of such a > package? My package veusz allows that... http://home.gna.org/veusz/ You can have any number of y-axes, see http://home.gna.org/veusz/screenshots/screenshot1.png The PyQt4 version is coming along nicely too... Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From robert.kern at gmail.com Thu Nov 2 14:36:12 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 02 Nov 2006 11:36:12 -0800 Subject: problem with svd in numpy In-Reply-To: References: Message-ID: Zeynep Gerek wrote: > Hello, > > I am having weird problem with svd routine in python. numpy questions are best asked on the numpy list. http://www.scipy.org/Mailing_Lists > I am comparing > eigenvector values from python and matlab. And they are giving different > values. Actually, they are same but python gives negative values of > these numbers. > > This is my test program (I am dealing with 100x100 matrices) with the > array I used in matlab. > I am not sure if svd in numpy has a problem or not. When I test this > matrix in matlab, eigenvector values are different, Any idea why I am > not getting exact results from both program? You didn't show what code you executed in Matlab. Did you also do an SVD there, or did you do an eigenvalue decomposition? The two are not the same thing. Which did you intend to do? In any case, it looks as if numpy_u == -matlab_u. How do numpy_vt and matlab_vt compare? Do they also have flipped signs? If so, then there is no problem. (u, vt) can be replaced with (-u, -vt). The SVD is not unique. Which one you get depends on the precise operations of the implementation. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From john106henry at hotmail.com Thu Nov 30 13:58:45 2006 From: john106henry at hotmail.com (John Henry) Date: 30 Nov 2006 10:58:45 -0800 Subject: Is there an easier way to express this list slicing? Message-ID: <1164913125.509492.54060@79g2000cws.googlegroups.com> If I have a list of say, 10 elements and I need to slice it into irregular size list, I would have to create a bunch of temporary variables and then regroup them afterwords, like: # Just for illustration. Alist can be any existing 10 element list a_list=("",)*10 (a,b,c1,c2,c3,d1,d2,d3,d4,d5)=a_list alist=(a,) blist=(b,) clist=(c1,c2,c3) dlist=(d2,d3,d4,d5) That obviously work but do I *really* have to do that? BTW: I know you can do: alist=a_list[0] blist=a_list[1] clist=a_list[2:5] dlist=a_list[5:] but I don't see that it's any better. Can I say something to the effect of: (a,b,c[0:2],d[0:5])=a_list # Obviously this won't work ?? I am asking this because I have a section of code that contains *lots* of things like this. It makes the code very unreadable. Thanks, From bdesth.quelquechose at free.quelquepart.fr Thu Nov 2 15:54:48 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 02 Nov 2006 21:54:48 +0100 Subject: scared about refrences... In-Reply-To: <1162412436.595926.66940@i42g2000cwa.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162251429.386255.289620@e3g2000cwe.googlegroups.com> <4547d0d7$0$7246$426a34cc@news.free.fr> <1162412436.595926.66940@i42g2000cwa.googlegroups.com> Message-ID: <454a5672$0$3721$426a74cc@news.free.fr> SpreadTooThin a ?crit : > Bruno Desthuilliers wrote: > >>Nick Vatamaniuc a ?crit : >>(snip) >> >>>In Python all the primitives are copied and all other entities are >>>references. >> >>Plain wrong. There's no "primitives" (ie : primitive data types) in >>Python, only objects. And they all get passed the same way. > > > so.. > def fn(x): > x = x + 1 > print x > > a = 2 > fn(a) > fn(2) > > Wouldn't you say that this is being passed by value rather than by > refrence? It's not passed by value. when in fn(), the *local* name 'x' is bound to (IOW:references) the exact same object you passed to fn(). Then you rebind this (local) name to *another* object. def fn((x): print id(x) x = x + 1 print id(x) n = 1256 print id(n) fn(n) def fn2(alist): print id(alist) alist.append(42) mylist = [] print id(mylist) fn2(mylist) print mylist print id(mylist) There's nothing like "pass by value" or "pass by reference" in Python (and you'll notice I didn't claimed anything about this - just that the 'argument passing scheme' was the same for all objects). What we call "variables" in Python are name=>object bindings. When passing a "variable" to a function, the reference to the objet is bound to the name of the argument in the function's namespace. So the *name* is local to the function (hence rebinding the name to another objet doesn't impact the name=>object binding in the caller's namespace), but this name really refers to the same object (Python doesn't copy anything unless explicitely told to do so). HTH From jonas.esp at googlemail.com Thu Nov 23 16:19:47 2006 From: jonas.esp at googlemail.com (GinTon) Date: 23 Nov 2006 13:19:47 -0800 Subject: Access to variable from external imported module Message-ID: <1164316786.875306.276460@h54g2000cwb.googlegroups.com> How to access to a variable (that value is not returned) from a module imported? And the variable is set at the module-level. That module is external to my program, it's from another project so I wann't modifying it. From john106henry at hotmail.com Wed Nov 8 15:36:30 2006 From: john106henry at hotmail.com (John Henry) Date: 8 Nov 2006 12:36:30 -0800 Subject: decorators Message-ID: <1163018190.510373.123020@h54g2000cwb.googlegroups.com> I must be very thick. I keep reading about what decorators are and I still don't have a good feel about it. See, for example: http://alex.dojotoolkit.org/?p=564 What exactly do I use decorators for? From kloro2006 at gmail.com Tue Nov 7 14:15:41 2006 From: kloro2006 at gmail.com (tom arnall) Date: Tue, 07 Nov 2006 11:15:41 -0800 Subject: object data member dumper? Message-ID: <4550cddd$0$12104$88260bb3@free.teranews.com> does anyone know of a utility to do a recursive dump of object data members? -- Posted via a free Usenet account from http://www.teranews.com From fredrik at pythonware.com Sat Nov 11 02:48:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Nov 2006 08:48:10 +0100 Subject: Py3K idea: why not drop the colon? In-Reply-To: <4554D010.4080408@hobbshouse.org> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <4554D010.4080408@hobbshouse.org> Message-ID: Michael Hobbs wrote: > Yeah, okay, I didn't read through the details of the PEP. I picked a bad > example to illustrate a point that is still true. The FAQ also tries to > argue that it's a Good Thing that join() is a string method, not a list > method. It also tries to argue that there's a good reason that lists are > different than tuples. I don't think it would surprising that many > Python developers don't really buy those arguments either. nice try, troll boy. From powernews at libero.it Mon Nov 27 08:01:03 2006 From: powernews at libero.it (halex2000) Date: Mon, 27 Nov 2006 13:01:03 GMT Subject: working with files and directories References: <7IAah.58105$uv5.416763@twister1.libero.it> Message-ID: "Thomas Ploch" ha scritto nel messaggio news:mailman.766.1164631069.32031.python-list at python.org... > Have you actually even tried to find some "documentation"? > Have you placed a google search "python directories rename files"? > Thomas Actually I did it on the documentation file provided with the windows distribution. I took a look at 11 ("File and Directory Access") but the listed functions doesn't appear to be what I need. 14.1.4 should do the job, but was not as intuitive to find as the previous one. From fredrik at pythonware.com Sat Nov 11 19:00:53 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Nov 2006 01:00:53 +0100 Subject: explicit self revisited In-Reply-To: <1163288444.893136.42030@h54g2000cwb.googlegroups.com> References: <1163288444.893136.42030@h54g2000cwb.googlegroups.com> Message-ID: Doug (Holton?) wrote: >> and before anyone complains; please note that they're working through >> >> http://www.effbot.org/pyfaq/design-index.htm > > That site is a bunch of FUD - the official FAQ is a bunch of FUD? are you sure you know what FUD means? From bumtool at gmail.com Thu Nov 23 07:35:28 2006 From: bumtool at gmail.com (kilnhead) Date: 23 Nov 2006 04:35:28 -0800 Subject: The Python Papers Edition One In-Reply-To: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> Message-ID: <1164285328.330478.95620@l12g2000cwl.googlegroups.com> I for one like the pdf format. Nothing irks me more than help files in multipage HTML. I want a document I can easily download and save. Thanks for your efforts. tleeuwenburg at gmail.com wrote: > Greetings all, > > Some of you may have noticed the launch of the Python Journal a while > back. Due to artistic differences, the journal has now been re-launched > as The Python Papers. It is available under a Creative Commons License, > something we felt was appropriate given its nature. Many here commented > that this was important to them, and it is important to us also. > > For a fuller description of what we hope the journal to be, I re-create > my inaugural blog posting at the end of this email, or it can be found > online here: http://pythonpapers.cgpublisher.com/diary > > Some of you had a number of specific points to raise, which I can now > answer properly since launching under our own banner. > > 1.) It takes too many clicks to download. > A) We know, but it's like that to save our server. We will be > publishing to a number of online archives, back-issues may be > back-linkable from those. > > 2.) Is it free? > A) Yes, as in beer and as in freedom. Creative Commons 2.5 > Noncommercial, attribution, share-alike. > > 3.) Can I have an HTML version? > A) No, we like it pretty. > > 4.) Why not try (insert favourite thing here) > A) We will. Thanks for the fish. > > " Volume 1, Edition 1 makes history > > Welcome to The Python Papers. This journal, small though it is, > represents the careful efforts of a small group of Python enthusiasts > who are keen to form a better community in which developers may work. > > As Editor-In-Chief, my role is manifold, but my goals are to improve > the level of connectedness of Python developers, and in so doing > improve my own developer experience. > > The entire editorial board has put time into making this publication > something which will hopefully lead to a buildup of momentum, fuelled > by the enthusiastic involvement of others who find Python as exciting > as we do. > > The current issue contains one academic, peer-reviewed article, one > industry article, and a list of events coming up in Melbourne, > Australia. We would like to expand this list significantly. We offer > our services in organising, collating and reviewing submitted content > such that Python developers around the world may participate in the > creation of something bigger than all of us, for the benefit of all of > us. It may be a small journal, a little thing really, but all are > welcome, and we look forward to getting to know our readers through the > written word. > > Please download the first edition, and consider both what it is and > what it might be. > > For those of you looking to publish an academic paper as a part of > coursework or for interest's sake alone, we can offer a formal review > process which will meet those guidelines while preserving the goals of > freedom of information and community spirit. > > Those who are using Python in their work may like to consider using the > journal as a means of expressing successes or frustrations with either > the language itself or specific applications. We may be able to offer > code reviews and style guides, and would be happy to hear about and > help propagate news of what is happening so that everyone can take an > interest. > > For those who would like a reliable source of information, The Python > Papers presents a unique and current view into the state of Python at > large. > > To all of you, welcome! > Cheers, > -Tennessee (Editor-In-Chief)" From roy at panix.com Wed Nov 1 23:14:56 2006 From: roy at panix.com (Roy Smith) Date: Wed, 01 Nov 2006 23:14:56 -0500 Subject: Regular Expression for a string References: <1162440285.962155.325540@f16g2000cwb.googlegroups.com> Message-ID: In article <1162440285.962155.325540 at f16g2000cwb.googlegroups.com>, "Teja" wrote: > HI all, > > I need to write a regular experssion for a string which satisfies the > following a criteria : > > 1) it should start with an alphabet I assume you mean, "It should start with a letter"? > 2) it can contain alphabets/digits/_ from second character > 3) it can contain "[a-z]" or "[0-9]" at the end. but this is optional How about: ^[a-zA-Z][a-zA-Z0-9_]*[a-z0-9]?$ Probably many variations on that theme will also work. From steve at holdenweb.com Tue Nov 14 05:55:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Nov 2006 10:55:24 +0000 Subject: Is python for me? In-Reply-To: References: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> Message-ID: Mark Woodward wrote: > On Mon, 13 Nov 2006 09:11:13 -0800, lennart wrote: > >> Hi, >> >> I'm planning to learn a language for 'client' software. Until now, i >> 'speak' only some web based languages, like php. As a kid i programmed >> in Basic (CP/M, good old days :'-) ) Now i want to start to learn a >> (for me) new computer language. >> >> I like Python. Its free, easy to learn and some favorite programs of my >> are written in Python / can understand Python (like OpenOffice) etc. >> >> But I'm not a full-time programmer. I know, that I've only time & >> possibility to learn one (= 1) language good. So i ask myself is python >> the language I'm looking for? > .... > > I've been hesitant to write this in the past but seems like a good time. > > I'm at the same stage, but (and this is NOT a troll) I'm tossing up > between Python and Ruby. I know this has been discussed numerous times but > I'd like to come at it from a different angle. > > I've been 'playing' with both languages and to be honest it's a case of 6 > of one, half a dozen of the other. If I'm using python I 'think' python > and if I'm using Ruby I 'think' ruby (if that makes sense). Ie I don't > find I'm more productive in one over the other to any great extent (pretty > unproductive in both ATM to be honest ;-)) . > > In the foreseeable future I suspect I'll stick with one and just use it > for things I personally will use/need. But (and here's where I finally get > to a question) I use Linux, I love the whole idea of open source and > contributing in some way. So if I ever get to the stage where I can give > something back is one preferred over the other? I would have thought no > but I read on the Ubuntu site somewhere that they prefer contributions > written in Python/ pyGTK?? Is this just a 'preference' or because python > is installed by default? (whereas Ruby isn't)? Is it just Ubuntu or Linux > distros in general? > > I hope you can see where I'm coming from here. I don't want to start a > Python/Ruby flame war. That's not the question. The question is "is one > preferred over the other when contributing software and is this just a > particular distros preference"? > Ubuntu is pretty much a Python-oriented distribution. A lot of people like it because you always get a fairly up-to-date Python with lots of extras available. I don't know that much about Ruby, but the best approach to software development has always been to choose the best language for solving the problem, so you seem to be doing OK. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From timothy at open-networks.net Thu Nov 16 07:07:41 2006 From: timothy at open-networks.net (timmy) Date: Thu, 16 Nov 2006 22:07:41 +1000 Subject: Secure Python In-Reply-To: References: <455c1665@quokka.wn.com.au> <455c4d07@quokka.wn.com.au> Message-ID: <455c5410@quokka.wn.com.au> Fredrik Lundh wrote: > timmy wrote: > >> maybe you should google "linux kernel limit" and you can prevent any >> user/process maxing out your system > > > one would have thought that the phrase "apart from OS-specific stuff" > might have meant that the OP wasn't asking for Linux-specific solutions. > > > sorry i didn't see that. cpu and memory limiting aren't specific to linux though, any NT system can also do it. the only effective way to prevent someone with access to a compiler from performing a local dos on your system is use each os's resource controls. there's no cross platform way to do this, since every system has vastly different methods of memory and cpu time handling. This looks like a case where he will just have to accept this as a trade off (security is always a trade off) From ronrsr at gmail.com Tue Nov 28 00:34:42 2006 From: ronrsr at gmail.com (ronrsr) Date: 27 Nov 2006 21:34:42 -0800 Subject: splitting a long string into a list Message-ID: <1164692082.272978.66720@14g2000cws.googlegroups.com> I have a single long string - I'd like to split it into a list of unique keywords. Sadly, the database wasn't designed to do this, so I must do this in Python - I'm having some trouble using the .split() function, it doesn't seem to do what I want it to - any ideas? thanks very much for your help. r-sr- longstring = 'Agricultural subsidies; Foreign aidAgriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development, Birth Defects; Toxic ChemicalsAntibiotics, AnimalsAgricultural Subsidies, Global TradeAgricultural SubsidiesBiodiversityCitizen ActivismCommunity GardensCooperativesDietingAgriculture, CottonAgriculture, Global TradePesticides, MonsantoAgriculture, SeedCoffee, HungerPollution, Water, FeedlotsFood PricesAgriculture, WorkersAnimal Feed, Corn, PesticidesAquacultureChemical WarfareCompostDebtConsumerismFearPesticides, US, Childhood Development, Birth DefectsCorporate Reform, Personhood (Dem. Book)Corporate Reform, Personhood, Farming (Dem. Book)Crime Rates, Legislation, EducationDebt, Credit CardsDemocracyPopulation, WorldIncomeDemocracy, Corporate Personhood, Porter Township (Dem. Book)Disaster ReliefDwellings, SlumsEconomics, MexicoEconomy, LocalEducation, ProtestsEndangered Habitat, RainforestEndangered SpeciesEndangered Species, Extinctionantibiotics, livestockAgricultural subsidies; Foreign aid;Agriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development, Birth Defects; Toxic Chemicals;Antibiotics, Animals;Agricultural Subsidies, Global Trade;Agricultural Subsidies;Biodiversity;Citizen Activism;Community Gardens;Cooperatives;Dieting;Agriculture, Cotton;Agriculture, Global Trade;Pesticides, Monsanto;Agriculture, Seed;Coffee, Hunger;Pollution, Water, Feedlots;Food Prices;Agriculture, Workers;Animal Feed, Corn, Pesticides;Aquaculture;Chemical Warfare;Compost;Debt;Consumerism;Fear;Pesticides, US, Childhood Development, Birth Defects;Corporate Reform, Personhood (Dem. Book);Corporate Reform, Personhood, Farming (Dem. Book);Crime Rates, Legislation, Education;Debt, Credit Cards;Democracy;Population, World;Income;Democracy, Corporate Personhood, Porter Township (Dem. Book);Disaster Relief;Dwellings, Slums;Economics, Mexico;Economy, Local;Education, Protests;Endangered Habitat, Rainforest;Endangered Species;Endangered Species, Extinction;antibiotics, livestock;Pesticides, Water;Environment, Environmentalist;Food, Hunger, Agriculture, Aid, World, Development;Agriculture, Cotton Trade;Agriculture, Cotton, Africa;Environment, Energy;Fair Trade (Dem. Book);Farmland, Sprawl;Fast Food, Globalization, Mapping;depression, mental illness, mood disorders;Economic Democracy, Corporate Personhood;Brazil, citizen activism, hope, inspiration, labor issues;citizen activism, advice, hope;Pharmaceuticals, Medicine, Drugs;Community Investing;Environment, Consumer Waste Reduction, Consumer Behavior and Taxes;Hunger, US, Poverty;FERTILITY, Women;Agricultural subsidies; Foreign aid;Agriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development, Birth Defects; Toxic Chemicals;Antibiotics, Animals;Agricultural Subsidies, Global Trade;Agricultural Subsidies;Biodiversity;Citizen Activism;Community Gardens;Cooperatives;Dieting;Agricultural subsidies; Foreign aid;Agriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development, Birth Defects; Toxic Chemicals;Antibiotics, Animals;Agricultural Subsidies, Global Trade;Agricultural Subsidies;Biodiversity;Citizen Activism;Community Gardens;Cooperatives;Dieting;Agriculture, Cotton;Agriculture, Global Trade;Pesticides, Monsanto;Agriculture, Seed;Coffee, Hunger;Pollution, Water, Feedlots;Food Prices;Agriculture, Workers;Animal Feed, Corn, Pesticides;Aquaculture;Chemical Warfare;Compost;Debt;Consumerism;Fear;Pesticides, US, Childhood Development, Birth Defects;Corporate Reform, Personhood (Dem. Book);Corporate Reform, Personhood, Farming (Dem. Book);Crime Rates, Legislation, Education;Debt, Credit Cards;' From walterbyrd at iname.com Wed Nov 15 10:58:05 2006 From: walterbyrd at iname.com (walterbyrd) Date: 15 Nov 2006 07:58:05 -0800 Subject: Python v PHP: fair comparison? In-Reply-To: References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> Message-ID: <1163606284.985813.294550@f16g2000cwb.googlegroups.com> Michael Torrie wrote: > Absolutely false. Most of my standalone, command-line scripts for > manipulating my unix users in LDAP are written in PHP, although we're > rewriting them in python. > I would say that you are one of very few who use PHP for sys-admin tasks - and even you have switched to Python. In general, it does not seem to me that PHP has caught on as a sys-admin language. However, as sys-admin scripting langanges go, I would also say that Python is far less popular than butt-ugly Perl. Again - just based on what I've seen. From daniel.dittmar at sap.com Fri Nov 3 12:34:57 2006 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Fri, 03 Nov 2006 18:34:57 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> Message-ID: robert wrote: > (IPython is only a special "python network terminal" as already said.) Sorry, I thought of IronPython, the .NET variant. > Does Jython really eliminate the GIL? What happens when different Yes. > threads alter/read a dict concurrently - the basic operation in python, > which is usually not protected by locks. Does Jython use a dict data > type (and other collection types) which lock during _each_ access? in > case - that may be very expensive. True, though Java synchronization has gotten better and better. Still, Sun introduced non locking hash tables, so it was a problem. It'd be interesting to know which kind of dict is used in Jython for attribute access. > > garbage is collected earliest, when the refcount went to 0. If it ever > went to 0, no one will ever use such object again. Thus GC should not be > different at all. Since Python 2.?, there's a mark-and-sweep garbage collection in addition to the reference counting scheme. This was put into Python to be able to reclaim object cycles. Daniel From robert.kern at gmail.com Mon Nov 13 22:36:51 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 13 Nov 2006 21:36:51 -0600 Subject: Test-driven development of random algorithms In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > I'm working on some functions that, essentially, return randomly generated > strings. Here's a basic example: > > def rstr(): > """Return a random string based on a pseudo > normally-distributed random number. > """ > x = 0.0 > for i in range(12): > x += random.random() > return str(int(x)+6)) > > I want to do test-driven development. What should I do? Generally, any > test I do of the form > > assert rst() == '1' > > will fail more often than not (about 85% of the time, by my estimate). An > easy work around would be to do this: > > assert rstr() in [str(n) for n in range(-6, 6)] > > but (1) that doesn't scale very well (what if rstr() could return one of > a billion different strings?) and (2) there could be bugs which only show > up probabilistically, e.g. if I've got the algorithm wrong, rstr() might > return '6' once in a while. > > Does anyone have generic advice for the testing and development of this > sort of function? "Design for Testability". In library code, never call the functions in the random module. Always take as an argument a random.Random instance. When testing, you can seed your own Random instance and all of your numbers will be the same for every test run. This kind of design is A Good Thing(TM) outside of unit tests, too. They aren't the only places where one might want to have full control over the sequence of random numbers. -- 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 sjmachin at lexicon.net Sun Nov 26 19:07:50 2006 From: sjmachin at lexicon.net (John Machin) Date: 26 Nov 2006 16:07:50 -0800 Subject: Generating header information using ElementTree In-Reply-To: <1164583078.233238.227010@45g2000cws.googlegroups.com> References: <1164574832.936947.69420@h54g2000cwb.googlegroups.com> <1164579522.671325.36260@14g2000cws.googlegroups.com> <4suidqF10rlh1U1@mid.uni-berlin.de> <1164583078.233238.227010@45g2000cws.googlegroups.com> Message-ID: <1164586070.655741.256800@h54g2000cwb.googlegroups.com> Craig wrote: > Great. Got that sorted. The problem I have now is that some of the > XML data is not copied across to the file when I have the text > information included. The number of characters that is lost is equal > to the number of characters that is in the block of text I entered > before. The code I am using is: > > def WriteXMLRecord ( record, XMLFileBaseName, root): > RecordName = SubElement(root, "Log") > #iterate through all the fields in the record > for key in record: > # write the key and its data > test = SubElement(RecordName, key) > test.text = str(record[key]) > tree = ElementTree(root) > tree.write(XMLFileBaseName) I'm guessing, based on reading the docs for the write method, that you should be using the file handle, rather than the file name, if the file is already opened. So (1) change the name of the 2nd arg to XMLFileHandle or somesuch, and in the caller, use outFile (the handle) instead of "record.xml". > > def main(): > outFile = open("record.xml", 'w') > outFile.write(""" > > \n\n""") > > root = Element("Log") > WriteXMLRecord(data1, "record.xml", root) > WriteXMLRecord(data2, "record.xml", root) > WriteXMLRecord(data3, "record.xml", root) > outFile.close() > HTH, John From svein at seldal dot com Thu Nov 9 08:44:25 2006 From: svein at seldal dot com (Svein Seldal) Date: Thu, 09 Nov 2006 14:44:25 +0100 Subject: Multithreaded C API Python questions In-Reply-To: References: Message-ID: <7vCdnSqE260grc7YRVnzvQ@telenor.com> robert wrote: > PyGILState_Ensure/Release guarantees to establish the GIL - even if it > was already held (useful if you deal with complex call > ordering/dependencies) I understand this to mean that I dont need to explicitly lock the GIL (with PyEval_AcquireLock() or PyEval_AcquireThread()). Well I cant figure out the PyGILState_Ensure() because if I only use this function to establish the GIL, when calling python, python will shortly after crash with "Fatal Python error: ceval: tstate mix-up". This happens consistently when the main app and the extra thread has called python and both are busy executing python code. > PyObject_CallObject(...) calls Python code. Thus the interpreter > will switch and do as usuall during that. BTW What do you mean by switch? > In your/C/system... code you are responsible to release the GIL or not > to enable other Python threads (and prevent from deadlocks) Usually > you'd do this * if you do time consuming C/system stuff > * or if the code can possibly renter Python through the system (e.g. > when you call a Windows function which itself can create Windows > messages to be routed back into Python message handlers) The main problem is that not done this way, it's the other way around. My main C app will call a python function which will be a lengthy time consuming process. The main C app will call python and it will never return from PyObject_CallObject(...), while the extra thread should call a py function to deliver occational messages into C. Svein From paul at boddie.org.uk Tue Nov 7 05:57:15 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 7 Nov 2006 02:57:15 -0800 Subject: Unicode/ascii encoding nightmare References: <1162842650.780517.180360@b28g2000cwb.googlegroups.com> <1162846153.137536.116970@b28g2000cwb.googlegroups.com> <1162853677.881233.76940@m7g2000cwm.googlegroups.com> Message-ID: <1162897035.238736.129220@k70g2000cwa.googlegroups.com> Thomas W wrote: > Ok, I've cleaned up my code abit and it seems as if I've > encoded/decoded myself into a corner ;-). Yes, you may encounter situations where you have some string, you "decode" it (ie. convert it to Unicode) using one character encoding, but then you later "encode" it (ie. convert it back to a plain string) using a different character encoding. This isn't a problem on its own, but if you then take that plain string and attempt to convert it to Unicode again, using the same input encoding as before, you'll be misinterpreting the contents of the string. This "round tripping" of character data is typical of Web applications: you emit a Web page in one encoding, the fields in the forms are represented in that encoding, and upon form submission you receive this data. If you then process the form data using a different encoding, you're misinterpreting what you previously emitted, and when you emit this data again, you compound the error. > My understanding of unicode has room for improvement, that's for sure. I got some pointers > and initial code-cleanup seem to have removed some of the strange results I got, which > several of you also pointed out. Converting to Unicode for processing is a "best practice" that you seem to have adopted, but it's vital that you use character encodings consistently. One trick, that can be used to mitigate situations where you have less control over the encoding of data given to you, is to attempt to convert to Unicode using an encoding that is "conservative" with regard to acceptable combinations of byte sequences, such as UTF-8; if such a conversion fails, it's quite possible that another encoding applies, such as ISO-8859-1, and you can try that. Since ISO-8859-1 is a "liberal" encoding, in the sense that any byte value or combination of byte values is acceptable, it should only be used as a last resort. However, it's best to have a high level of control over character encodings rather than using tricks to avoid considering representation issues carefully. Paul From johnjsal at NOSPAMgmail.com Thu Nov 2 22:07:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 02 Nov 2006 22:07:10 -0500 Subject: creating new objects with references to them In-Reply-To: References: <1162480549.786082.290980@b28g2000cwb.googlegroups.com> <1162486298.863881.261790@h54g2000cwb.googlegroups.com> Message-ID: <454ab276$0$17722$c3e8da3@news.astraweb.com> Dennis Lee Bieber wrote: > I'd keep it -- since the operations to load/save from the database > should probably be methods of that class -- or, at least, the mapping > from instance attributes to the SQL might be... Well, I'm sort of working on a method that just involves a bunch of functions doing all the work. Maybe not ideal. I think I need to take your advice about stepping back and looking at it again. From p.lavarre at ieee.org Fri Nov 10 09:14:43 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 10 Nov 2006 06:14:43 -0800 Subject: FAQ: How do I calculate what quoted strings and numbers mean? Message-ID: <1163168083.054745.32170@f16g2000cwb.googlegroups.com> > Subject: announce: FAQs suggested ... > http://effbot.org/pyfaq/suggest.htm has new FAQ's ... > FAQ: How do I calculate what quoted strings and numbers mean? > > A: eval(source, {'builtins': {}}) works, without also accidentally > accepting OS commands as input. > > Note: Eval might surprise you if you mistype this idiom as: eval(source, {}). > > Note: This idiom makes sense of ordinary Python literals (such as 010, 0x8, > 8.125e+0, and "\x45ight"). This idiom also correctly interprets simple > literal expressions, such as 64**0.5. That suggested FAQ is misleadingly incorrect as stated - we need help rewording it. /F correctly commented: "eval" is never a good choice if you cannot trust the source; it's trivial to do various denial-of-service attacks. See http://effbot.org/zone/librarybook-core-eval.htm Correspondingly, newbie me, I actually did copy the eval(source, {'builtins': {}}) idiom into some code from that page without noticing the comments re the cost of evaluating literal expressions like 'a' * (10**9) , abuses of __subclass__ and mro(), etc. But those objections miss the point. Having had those troubles explained to me now, I'm still leaving my code unchanged - it still does what I mean. That is, eval(source, {'builtins': {}}) works enough like an evaluator of literals to let you duck the work of writing that evaluator until you need it. Yagni. That's useful, and likely an FAQ. Anybody out there able to say concisely what we really mean to say here? Thanks in advance, Pat LaVarre From e0427417 at student.tuwien.ac.at Mon Nov 20 10:43:08 2006 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Mon, 20 Nov 2006 16:43:08 +0100 Subject: a few extensions for the itertools In-Reply-To: References: <4560bfb0$0$10578$3b214f66@tunews.univie.ac.at> <45616b46$0$12642$3b214f66@tunews.univie.ac.at> Message-ID: <4561ccac$0$11610$3b214f66@tunews.univie.ac.at> Duncan Booth wrote: > Mathias Panzenboeck wrote: > >> No, because the builtin sum want's a list. This can also handle any >> kind of iterable, so this would work: >> >> isum(i**2 for i in xrange(100)) >> >> sum would need firs the whole list to be generated: >> >> sum([i**2 for i in xrange(100)]) > > Really? > >>>> sum(i**2 for i in xrange(20000000)) > 2666666466666670000000L > > seems to work fine, and judging by the memory usage it pretty obviously > doesn't create an intermediate list. Very strange. I must have made some strange error. I tried that (more than once) and it failed. Don't know why. But now it works here, too. What did I write, when it failed? From dananrg at yahoo.com Wed Nov 8 07:25:15 2006 From: dananrg at yahoo.com (dananrg at yahoo.com) Date: 8 Nov 2006 04:25:15 -0800 Subject: More elegant way to obtain ACLs / permissions for windows directories than using "cacls" dos command? In-Reply-To: <1162988020.060319.124030@b28g2000cwb.googlegroups.com> References: <1162933222.244854.135180@f16g2000cwb.googlegroups.com> <1162952479_41619@sp6iad.superfeed.net> <1162988020.060319.124030@b28g2000cwb.googlegroups.com> Message-ID: <1162988715.639810.125270@f16g2000cwb.googlegroups.com> Could you give an example for listing security descriptors using the win32security module? I looked at the documentation but found it confusing. Thanks. From fredrik at pythonware.com Sat Nov 11 10:26:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Nov 2006 16:26:54 +0100 Subject: import parser does not import parser.py in same dir on win In-Reply-To: References: Message-ID: Joel Hedlund wrote: > It turns out that on Windows, the builtin parser module is imported > instead. Why? the table of built-in modules are checked before searching the path. > Why is there a difference? What other names are "taken"? depends on how the interpreter is built; there's a sys variable that contains a list of all built-ins: http://effbot.org/pyref/sys.builtin_module_names From grante at visi.com Fri Nov 3 16:01:51 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 03 Nov 2006 21:01:51 -0000 Subject: py2exe questions References: Message-ID: <12knbhvnnaksh68@corp.supernews.com> On 2006-11-03, Doug Stell wrote: > I have 2 questions about py2exe or any similar utility. > > 1. Is it possible to create a single Windows executable that does not > blow out to a folder full of files and can be called from scripts > using command line arguments? The default operation of py2exe already meets requirement 1b: an executable that can be called from scripts using command line arguments. -- Grant Edwards grante Yow! Now I'm concentrating at on a specific tank battle visi.com toward the end of World War II! From chrispearl at gmail.com Thu Nov 2 00:55:45 2006 From: chrispearl at gmail.com (Chris Pearl) Date: Thu, 2 Nov 2006 07:55:45 +0200 Subject: Python tools for managing static websites? In-Reply-To: <1162331694.836988.322220@m73g2000cwd.googlegroups.com> References: <1162331694.836988.322220@m73g2000cwd.googlegroups.com> Message-ID: Thanks to everyone who have contributed to this thread. Several of the posted suggestions definitely warrant a closer look. I'm going to review those and publish my final choice - including the reasons for it - if anyone's interested. -Chris From gagsl-py at yahoo.com.ar Fri Nov 10 18:45:14 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 10 Nov 2006 20:45:14 -0300 Subject: urlretrieve get file name In-Reply-To: <1163188701.981923.18960@h48g2000cwc.googlegroups.com> References: <1163110313.580268.19660@h48g2000cwc.googlegroups.com> <1163116359.787681.31490@m73g2000cwd.googlegroups.com> <1163188701.981923.18960@h48g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20061110204024.0470c078@yahoo.com.ar> At Friday 10/11/2006 16:58, Sven wrote: >Yes the browser suggests a file name, but I did a little research using >http://web-sniffer.net/. The Response Header contains roughly this: > >HTTP Status Code: HTTP/1.1 302 Found >Location: http://page.com/filename.zip >Content-Length: 0 >Connection: close >Content-Type: text/html > >The status code 302 tells the browser where to find the file. The funny >thing is that calling the info() function, on the file-like response >object, in Python doesn't return the same header. I'm so stuck. :-) >Thanks for your help. Because urlopen is smart enough to detect the redirection and do a second request. You can use the geturl() method to obtain the true URL used (that would be http://page.com/filename.zip) and then rename the file. Or, you can install your own URLOpener (I think a FancyURLOpener with retries=0 would be OK) and process the Location header yourself. See the urllib documentation. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From horpner at yahoo.com Wed Nov 15 09:20:35 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 15 Nov 2006 15:20:35 +0100 Subject: refactoring so that multiple changes can be made with one variable? References: <4559e396$0$32430$c3e8da3@news.astraweb.com> Message-ID: On 2006-11-15, Dennis Lee Bieber wrote: > On Wed, 15 Nov 2006 18:57:39 +1100, Steven D'Aprano > declaimed the following in > comp.lang.python: >> And last but most certainly not least, you can separate the >> adjustment values into (say) an INI file, read them in at >> run-time and pass those values to the factory function above. >> Then write another function which walks through the INI file, >> adjusting the values in place as needed. This is obviously >> going to take the most work, so I strongly suggest you don't >> go down this path unless you really have to. > > Nice to see I wasn't the only one to consider extending to an > INI file for this Coincidentally, I'm just reading "The Pragmattic Programmer" for the first time. One of guidelines is to pry the details ut of the code if they might change. The above advice seems like a perfect example. -- Neil Cerutti For those of you who have children and don't know it, we have a nursery downstairs. --Church Bulletin Blooper From george.sakkis at gmail.com Mon Nov 13 10:00:16 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 13 Nov 2006 07:00:16 -0800 Subject: Python 3000 idea -- + on iterables -> itertools.chain References: <1163385266.824914.265490@b28g2000cwb.googlegroups.com> <1163408380.747399.18750@h54g2000cwb.googlegroups.com> <1163417909.768399.199650@h54g2000cwb.googlegroups.com> Message-ID: <1163430016.542861.130100@b28g2000cwb.googlegroups.com> Carl Banks wrote: > George Sakkis wrote: > > Fredrik Lundh wrote: > > > > > George Sakkis wrote: > > > > > > > The base object class would be one candidate, similarly to the way > > > > __nonzero__ is defined to use __len__, or __contains__ to use __iter__. > > > > > > > > Alternatively, iter() could be a wrapper type (or perhaps mixin) > > > > instead of a function, something like: > > > > > > so you're proposing to either make *all* objects respond to "+", or > > > introduce limited *iterator* algebra. > > > > If by 'respond to "+"' is implied that you can get a "TypeError: > > iterable argument required", as you get now for attempting "x in y" for > > non-iterable y, why not ? > > Bad idea on many, many levels. Don't go there. Do you also find the way "in" works today a bad idea ? > > Although I like the iterator algebra idea > > better. > > > > > not sure how that matches the OP's wish for "mostly backwards > > > compatible" support for *iterable* algebra, really... > > > > Given the subject of the thread, backwards compatibility is not the > > main prerequisite. Besides, it's an *extension* idea; allow operations > > that were not allowed before, not the other way around or modifying > > existing semantics. > > You missed the important word (in spite of Fredrick's emphasis): > iterable. Your iter class solution only works for *iterators* (and not > even all iterators); the OP wanted it to work for any *iterable*. I didn't miss the important word, I know the distinction between iterables and iterators; that's why I said I like the iterator algebra idea better (compared to extending the object class so that effectively creates an iterable algebra). > "Iterator" and "iterable" are protocols. The only way to implement > what the OP wanted is to change iterable protocol, which means changing > the documentation to say that iterable objects must implement __add__ > and that it must chain the iterables, and updating all iterable types > to do this. Besides the large amount of work that this will need, > there are other problems. > > 1. It increases the burden on third party iterable developers. > Protocols should be kept as simple as possible for this reason. > 2. Many iterable types already implement __add__ (list, tuple, string), > so this new requirement would complicate these guys a lot. If __add__ was ever to be part of the *iterable* protocol, it would be silly to implement it for every new iterable type; the implementation would always be the same (i.e. chain(self,other)), so it should be put in a base class all iterables extend from. That would be either a mixin class, or object. This is parallel to how __contains__ is part of the sequence protocol, but if you (the 3rd party sequence developer) don't define one, a default __contains__ that relies on __getitem__ is created for you. > > Of course, programs that attempt forbidden > > expressions on purpose so that they can catch and handle the exception > > would break when suddenly no exception is raised, but I doubt there are > > many of those... > > 3. While not breaking backwards compatibility in the strictest sense, > the adverse effect on incorrect code shouldn't be brushed aside. It > would be a bad thing if this incorrect code: > > a = ["hello"] > b = "world" > a+b > > suddenly started failing silently instead of raising an exception. That's a good example for why I prefer an iterator rather than an iterable algebra; the latter is too implicit as "a + b" doesn't call only __add__, but __iter__ as well. On the other hand, with a concrete iterator type "iter(a) + iter(b)" is not any more error-prone than 'int(3) + int("2")' or 'str(3) + str("2")'. What's the objection to an *iterator* base type and the algebra it introduces explicitly ? George From jeremy+complangpython at jeremysanders.net Tue Nov 14 09:08:50 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 14 Nov 2006 14:08:50 +0000 Subject: Programmatically finding "significant" data points References: <1163513101.580610.151420@b28g2000cwb.googlegroups.com> Message-ID: erikcw wrote: > I have a collection of ordered numerical data in a list. The numbers > when plotted on a line chart make a low-high-low-high-high-low (random) > pattern. I need an algorithm to extract the "significant" high and low > points from this data. > ... > > How do I sort through this data and pull out these points of > significance? Get a book on statistics. One idea is as follows. If you expect the points to be centred around a single value, you can calculate the median or mean of the points, calculate their standard deviation (aka spread), and remove points which are more than N-times the standard deviation from the median. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From steve at holdenweb.com Thu Nov 2 17:46:22 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Nov 2006 22:46:22 +0000 Subject: scared about refrences... In-Reply-To: <1162506227.070059.230550@h54g2000cwb.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162251429.386255.289620@e3g2000cwe.googlegroups.com> <4547d0d7$0$7246$426a34cc@news.free.fr> <1162412436.595926.66940@i42g2000cwa.googlegroups.com> <454a5672$0$3721$426a74cc@news.free.fr> <1162506227.070059.230550@h54g2000cwb.googlegroups.com> Message-ID: SpreadTooThin wrote: > Bruno Desthuilliers wrote: > >>SpreadTooThin a ?crit : >> >>>Bruno Desthuilliers wrote: >>> >>> >>>>Nick Vatamaniuc a ?crit : >>>>(snip) >>>> >>>> >>>>>In Python all the primitives are copied and all other entities are >>>>>references. >>>> >>>>Plain wrong. There's no "primitives" (ie : primitive data types) in >>>>Python, only objects. And they all get passed the same way. >>> >>> >>>so.. >>>def fn(x): >>> x = x + 1 >>> print x >>> >>>a = 2 >>>fn(a) >>>fn(2) >>> >>>Wouldn't you say that this is being passed by value rather than by >>>refrence? >> >>It's not passed by value. when in fn(), the *local* name 'x' is bound to >>(IOW:references) the exact same object you passed to fn(). Then you >>rebind this (local) name to *another* object. >> >>def fn((x): >> print id(x) >> x = x + 1 >> print id(x) >> >>n = 1256 >>print id(n) >>fn(n) >> >>def fn2(alist): >> print id(alist) >> alist.append(42) >> >>mylist = [] >>print id(mylist) >>fn2(mylist) >>print mylist >>print id(mylist) >> >> >>There's nothing like "pass by value" or "pass by reference" in Python >>(and you'll notice I didn't claimed anything about this - just that the >>'argument passing scheme' was the same for all objects). >> >>What we call "variables" in Python are name=>object bindings. When >>passing a "variable" to a function, the reference to the objet is bound >>to the name of the argument in the function's namespace. So the *name* >>is local to the function (hence rebinding the name to another objet >>doesn't impact the name=>object binding in the caller's namespace), but >>this name really refers to the same object (Python doesn't copy anything >>unless explicitely told to do so). >> >>HTH > > > > I realize I may be beating a dead horse here... but... > You are! > a = 2 > fn(a) > >>>>3 > > print a > >>>>2 > > > So in some cases the it is safe to assume that your variables to > function will not > change in other cases it is not.. but they are all the same... > Mutable values can be mutated. Immutable ones can't. Please stop worrying and start enjoying Python. Once you have started cutting code you will wonder why you ever bothered to spend so much time on this issue. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From hg at nospam.com Wed Nov 22 09:58:50 2006 From: hg at nospam.com (hg) Date: Wed, 22 Nov 2006 08:58:50 -0600 Subject: Python visual IDE In-Reply-To: <1164206609.276356.165670@m73g2000cwd.googlegroups.com> References: <1164188410.516169.171150@f16g2000cwb.googlegroups.com> <1164205868.349589.217040@k70g2000cwa.googlegroups.com> <1164206609.276356.165670@m73g2000cwd.googlegroups.com> Message-ID: <_DZ8h.3237$pM.2926@newsfe13.lga> king kikapu wrote: > I have already downloaded and seen the trial of Komodo Professional. > Indeed it has a simple Gui Builder but one can only use TKinter on it. > No wxWidgets support and far from truly RAD, but it is the only > "integrated" > GUI builder in these IDEs... > > > On Nov 22, 4:31 pm, "Steve" wrote: >> I haven't used it but Komodo (Professional version) says it has: >> >> ActiveState GUI Builder (Komodo Professional only) >> >> Enhance your applications with GUI dialogs: Simple, Tk-based dialog >> builder with seamless round-trip integration, for Perl, Python, Ruby, >> and Tcl. > I do a lot of GUI programming with wxPython. I find that switching from desktop 1 (Eclipse/PyDev) to desktop 2 (wxDesigner) becomes a reflex quite quickly ... even under Windows thanks to virtuawin (http://virtuawin.sourceforge.net) - both packages also are smart enough to notice when an open file has been modified elsewhere. I also program in Visual-Studio and overall do not find the RAD/IDE integration that much more convenient. Also, I generally get the job done in wxDesigner at the beginning of the project, and seldom have to get back into it to twick the interface. hg From _karlo_ at _mosor.net_ Sun Nov 5 19:56:26 2006 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Mon, 6 Nov 2006 00:56:26 +0000 (UTC) Subject: wing ide vs. komodo? References: <2nRXg.108$1n3.2866@news.tufts.edu> <1162690929.501897.258360@b28g2000cwb.googlegroups.com> <1162708898.962171.161120@e3g2000cwe.googlegroups.com> Message-ID: "vj" wrote in news:1162708898.962171.161120 @e3g2000cwe.googlegroups.com: > The embedded python shell is also a useful feature. Yes, but Debug Probe and Stack Data absolutely rock! Can't live without them anymore. Just set a breakpoint, run your code end then you can inspect all of the structures via Stack Data, and you can play with those structures using Debug Probe. Huge productivity boost... -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From no-spam at no-spam-no-spam.invalid Thu Nov 23 17:34:37 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 23 Nov 2006 23:34:37 +0100 Subject: Access to variable from external imported module In-Reply-To: <1164319761.451409.196660@j44g2000cwa.googlegroups.com> References: <1164316786.875306.276460@h54g2000cwb.googlegroups.com> <1164319761.451409.196660@j44g2000cwa.googlegroups.com> Message-ID: GinTon wrote: > Sorry, I mean access to local variable from a method > > import module > method(value) > > I would to access to values that are created locally in that method after the method has executed? usually the return value? or you want to get all local variables, then make a func/method def f(a=1): b=2 c=3 return locals() #X/Object(locals()) -------- d=module.f() print d['c'] # d.c Robert From fd0man at gmail.com Fri Nov 17 15:10:51 2006 From: fd0man at gmail.com (Michael B. Trausch) Date: Fri, 17 Nov 2006 15:10:51 -0500 Subject: Decimal() instead of float? In-Reply-To: References: <1163294604.4675.4.camel@pepper> <1163511997.4675.88.camel@pepper> <4559F828.7070704@holdenweb.com> Message-ID: <1163794251.5107.151.camel@pepper> On Wed, 2006-11-15 at 12:48 +0100, Fredrik Lundh wrote: > Steve Holden wrote: > > >> It /would/ be nice to see Decimal() become the default. I cannot > >> imagine why in an otherwise "human enough" language, math wouldn't be > >> included in that without going out of one's way to do it. :-) > >> > > Speed has a lot to do with it. Have you timed some decimal operations > > against their floating-point counterparts? It might be possible to build > > a version of Python that used decimal instead of floating-point but it > > certainly wouldn't be trivial: consider the use of C language libraries > > that know nothing of Python's decimal representation. > > judging from the various decimal FAQ:s, I think it's a bit naive to > think that using Decimal instead of float would somehow make everything > "just work": > > http://www2.hursley.ibm.com/decimal/decifaq.html > http://effbot.org/pylib/decimal.htm#decimal-faq > > (btw, the OP mentioned in private mail that he wanted to store > geographical coordinates in decimal because floats kept messing things > up, but given that a 64-bit float can hold enough decimal digits to > represent a geographical coordinate with sub-millimeter precision on a > global scale, I'm not sure I buy that argument. I suspect he was just > tricked by the usual repr(1.15) != "1.15" issue. and seriously, under- > standing the various aspects of floats and decimals is utterly trivial > compared to all the nearly-magical things you need to understand to be > able to do geographical calculations at a sub-millimeter scale. heck, > even sub-kilometer stuff is pretty hard to get right ;-) I don't have (so far as I know) a 64-bit float available to me. Some of the lat/long pairs that I have used seem to come out fine, but some do not. Because the mathmatics used with them involve complex equations when determining distance and the like, any error gets massively compounded before a final result is evident. Thus, the numbers must be exact. That's why I originally asked if Decimal() can be used instead. Since it cannot, that's fine, I will just use Decimal(), assuming that it supports everything that I will need to do with the numbers. If not, then I guess I will have to look at something that uses GMP. -- Mike -- Michael B. Trausch fd0man at gmail.com Phone: (404) 592-5746 Jabber IM: fd0man at livejournal.com Demand Freedom! Use open and free protocols, standards, and software! -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Wed Nov 22 15:03:25 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 22 Nov 2006 14:03:25 -0600 Subject: regex problem In-Reply-To: References: Message-ID: <4564AD0D.80806@tim.thechases.com> > line is am trying to match is > 1959400|Q2BYK3|Q2BYK3_9GAMM Hypothetical outer membra 29.9 0.00011 1 > > regex i have written is > re.compile > (r'(\d+?)\|((P|O|Q)\w{5})\|\w{3,6}\_\w{3,5}\s+?.{25}\s{3}(\d+?\.\d)\s+?(\d\.\d+?)') > > I am trying to extract 0.0011 value from the above line. > why doesnt it match the group(4) item of the match ? > > any idea whats wrong with it ? Well, your ".{25}\s{3}" portion only gets you to one space short of your 29.9, so your "(\d+..." fails to match " 29.9" because there's an extra space there. My guess (from only one datum, so this could be /way/ off base) would be that you mean "\s{4}" or possibly "\s{3,4}" It seems like a very overconstrained regexp, but it might be just what you need to isolate the single line (or class of line) amongst the chaff of thousand others of similar form. -tkc From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Nov 19 07:18:39 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 19 Nov 2006 13:18:39 +0100 Subject: tempfile.NamedTemporaryFile wont work References: <456049ca$0$4692$426a74cc@news.free.fr> Message-ID: <4sb0cvFurjq2U1@mid.individual.net> Imbaud Pierre wrote: > tf = tempfile.NamedTemporaryFile() > tfName = tf.name > [...] > print >> sys.stderr, '%s: %s' % (tfName, ['no', > 'yes'][os.path.exists(tfName)]) > subprocess.Popen(['strings', tfName]) Just out of curiosity: Why did you assign tf.name to tfname? Hypothetically, if tf.name changed, tfname wouldn't follow since strings are immutable. Regards, Bj?rn -- BOFH excuse #149: Dew on the telephone lines. From st at tobiah.org Fri Nov 3 16:09:49 2006 From: st at tobiah.org (tobiah) Date: Fri, 03 Nov 2006 13:09:49 -0800 Subject: WSDL? Message-ID: <454ba334$0$12110$88260bb3@free.teranews.com> Is WSDL the right answer for in house communication between programs written in different languages, or is it more for publishing interfaces for use by parties outside your own company? What else is available for sharing complex structures with processes running programs that were written in other languages? Thanks, Toby -- Posted via a free Usenet account from http://www.teranews.com From gheorghe.postelnicu at gmail.com Thu Nov 30 10:37:40 2006 From: gheorghe.postelnicu at gmail.com (Gheorghe Postelnicu) Date: Thu, 30 Nov 2006 10:37:40 -0500 Subject: Threading Message-ID: <8094b1b60611300737n36a51b47n40ab5ed4b770bc78@mail.gmail.com> Hi, I have a very simple Python script that performs some batch processing as follows: a list of system commands is set up in an automated way and then each of the processes is launched separately using threads - a basic producer-consumer thing. I found a recipe on ASPN on how to intercept keyboard interrupts and that is useful if I need to brutally kill the launching process. However, my question regards killing the actual children threads - they are spending lots of time in system calls, so I cannot insert some while loop in a derived Thread class. Any suggestions would be apreciated. Thanks, -- Gheorghe Postelnicu, PhD MGH, Harvard Medical School From Roberto.Bonvallet at cern.ch Wed Nov 1 08:47:49 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Wed, 1 Nov 2006 13:47:49 +0000 (UTC) Subject: Why can't you assign to a list in a loop without enumerate? References: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> <4qrln8Fo2ollU1@individual.net> Message-ID: Bjoern Schliessmann wrote: > Fredrik Lundh wrote: > >> what's wrong with using enumerate? or a list comprehension? or >> some other of the many different ways you can use to build a list >> from a set of values? > > Shouldn't there be one -- and preferably only one -- obvious way to > do it? 8) The obvious one is to use enumerate. TOOWTDI allows less obvious ways to exist. -- Roberto Bonvallet From theller at ctypes.org Thu Nov 23 11:25:52 2006 From: theller at ctypes.org (Thomas Heller) Date: Thu, 23 Nov 2006 17:25:52 +0100 Subject: select() on WinXP In-Reply-To: <1164298634.189031.282560@h54g2000cwb.googlegroups.com> References: <1164296300.268074.250230@j44g2000cwa.googlegroups.com> <1164298634.189031.282560@h54g2000cwb.googlegroups.com> Message-ID: <4565CB90.7060602@ctypes.org> grebekel at gmail.com schrieb: > I'm using it for sockets, it works on linux but not on Windows. The > actual code is something like (server side): > > r, w, e = select.select(self.clients, [], self.clients, 5) > > where self.clients is a list of accepted sockets. > The docs for select.select say: Empty sequences are allowed, but acceptance of three empty sequences is platform-dependent. (It is known to work on Unix but not on Windows.) Thomas From fredrik at pythonware.com Wed Nov 1 01:24:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 01 Nov 2006 07:24:50 +0100 Subject: 3d programming without opengl In-Reply-To: <4547cc58$0$11970$afc38c87@news.optusnet.com.au> References: <12kf7gishr60ta3@corp.supernews.com> <4547cc58$0$11970$afc38c87@news.optusnet.com.au> Message-ID: Richard Jones wrote: >> Pure Python doesn't necessarily imply "no graphics drawing code written >> in some other language", though. You can get pretty far by using a 2D >> library for simple 3D rendering. > > Someone wrote a 3D demo for the pygame.draw challenge*. It worked but > unfortunately he didn't end up finishing and submitting it. It had severe > performance limitations :) someone just posted this to reddit: http://www.uselesspickles.com/triangles/demo.html which I'd say qualifies as simple 3D with pretty decent performance given what it does and what platform it runs on... From podi.ex at gmail.com Wed Nov 22 19:27:57 2006 From: podi.ex at gmail.com (Podi) Date: 22 Nov 2006 16:27:57 -0800 Subject: windows background process Message-ID: <1164241677.007294.122880@k70g2000cwa.googlegroups.com> Hi, I am using Python 2.4.4 on Windows XP SP2. I am trying to start a process (infinite loop application) in the background and I've tried several options and none of them seem to work. Any help would be much appreciated. Thanks, P 1. # This works on PythonWin interactive window, but the python.exe process hangs until mycmd.exe process dies >>> os.popen("mycmd.exe myargs") # works if __name__ == '__main__': os.popen("mycmd.exe myargs") # hangs 2. >>> os.system("mycmd.exe myargs") # hangs, as expected 3. os.spawnl(os.P_NOWAIT, 'mycmd.exe', 'myargs') # mycmd.exe not started os.spawnv(os.P_NOWAIT, 'mycmd.exe', tuple('myargs')) # mycmd.exe not started 4. # Works, but not portable. My code is expected to run on *nix later on os.system('start /B "dummy title" "mycmd.exe" myargs') From steve at REMOVE.THIS.cybersource.com.au Tue Nov 7 09:44:31 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 08 Nov 2006 01:44:31 +1100 Subject: create global variables?-the full story References: <1162275890.4546ec32cd351@www2.helsinki.fi> <45471B66.9060702@helsinki.fi> Message-ID: On Tue, 07 Nov 2006 12:54:36 +0200, Alistair King wrote: > Does anyone knows of a simple way of > determining how much processer time it takes to do these calculations? See the timeit module. -- Steven. From Anthon.van.der.Neut at googlemail.com Tue Nov 14 07:08:57 2006 From: Anthon.van.der.Neut at googlemail.com (Anthon) Date: 14 Nov 2006 04:08:57 -0800 Subject: Python 2.5 Core Dump on Solaris 8 In-Reply-To: References: Message-ID: <1163506137.477368.111160@h48g2000cwc.googlegroups.com> Hi Melissa, I run into similar problems after compiling python-ldap 2.2.0 for Python 2.5 on SuSE Linux 9.3 and running a small commandline application *** glibc detected *** double free or corruption (out): 0x40180788 *** I realy suspect the _ldap.so file. I have not found a solution yet, but will let you know if I do. Did you compile python-ldap yourself for Python 2.5? Which version of python-ldap? Which compiler? Regards Anthon Melissa Evans wrote: > Hi. I'm new to Python. :) > > I've modified grappy.py, > http://www.stacken.kth.se/~mattiasa/projects/grappy/, a postfix policy > daemon for greylisting. to use LDAP as a backend instead of SQL (with > python-ldap.) The daemon runs fine when testing but when I put it under > load it core dumps quickly. What little analysis I know how to do shows > similar information every time. Any advice on where to go from here? > > Thanks! > Melissa > From gagsl-py at yahoo.com.ar Wed Nov 8 14:23:23 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 08 Nov 2006 16:23:23 -0300 Subject: please help with optimisation of this code - update of given table according to another table In-Reply-To: <1162981094.820174.65440@b28g2000cwb.googlegroups.com> References: <1162981094.820174.65440@b28g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061108161834.05a83d18@yahoo.com.ar> At Wednesday 8/11/2006 07:18, Farraige wrote: > for row_t1 in t1: > for row_t2 in t2: > if [row_t1[i] for i in keyColumns] == [row_t2[j] for j >in keyColumns]: > # the keys are the same > for colName in columnsToBeUpdated: > row_t1[colName] = row_t2[colName] > > # go outside the inner loop - we found a row with > # the same key in the table > break > >In my algorithm I have 2 for loops and I have no idea how to optimise >it (maybe with map? ) >I call this method for very large data and the performance is a >critical issue for me :( def getkey(row): return tuple([row[i] for i in keyColumns]) Sort both tables using .sort(key=getkey); then traverse both in paralell like in classic merge; in 1 pass you get the job done (not counting the two initial sorts) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From sandysj at juno.com Thu Nov 16 11:04:02 2006 From: sandysj at juno.com (Jeff Sandys) Date: 16 Nov 2006 08:04:02 -0800 Subject: matplotlib real time grap. In-Reply-To: <1163664130.657647.260620@e3g2000cwe.googlegroups.com> References: <1163664130.657647.260620@e3g2000cwe.googlegroups.com> Message-ID: <1163693042.604213.235510@m73g2000cwd.googlegroups.com> It sounds like you need a stripchart like: http://jstripchart.sourceforge.net/ written in Python of course. On Nov 16, 12:02 am, "luca72" wrote: ... > > with this i have the grap on the screen but i have to update every time > that i receive others data coming from two instruments (10 seconds), > how i can update the grap? > > Regards > > Luca From outstretchedarm at hotmail.com Fri Nov 3 16:10:08 2006 From: outstretchedarm at hotmail.com (Omar) Date: 3 Nov 2006 13:10:08 -0800 Subject: Programming Language that is Spreadsheet/Table Based Message-ID: <1162588208.533235.266100@k70g2000cwa.googlegroups.com> I'm looking for a programming language or module that sorta looks and feels like MS Excel (I love and think in tables), yet has the power and open-endedness of python or javascript. I'm still pretty new to python. any ideas? i've been having some fun with VBA in excel, but I want something I can save as en exe and call my own creation, y'know? From Thomas.Ploch at gmx.net Thu Nov 30 15:07:10 2006 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Thu, 30 Nov 2006 21:07:10 +0100 Subject: Is there an easier way to express this list slicing? In-Reply-To: <1164913125.509492.54060@79g2000cws.googlegroups.com> References: <1164913125.509492.54060@79g2000cws.googlegroups.com> Message-ID: <456F39EE.90206@gmx.net> John Henry schrieb: > If I have a list of say, 10 elements and I need to slice it into > irregular size list, I would have to create a bunch of temporary > variables and then regroup them afterwords, like: > > # Just for illustration. Alist can be any existing 10 element list > a_list=("",)*10 > (a,b,c1,c2,c3,d1,d2,d3,d4,d5)=a_list > alist=(a,) > blist=(b,) > clist=(c1,c2,c3) > dlist=(d2,d3,d4,d5) > > That obviously work but do I *really* have to do that? > > BTW: I know you can do: > alist=a_list[0] > blist=a_list[1] > clist=a_list[2:5] > dlist=a_list[5:] > > but I don't see that it's any better. > > Can I say something to the effect of: > > (a,b,c[0:2],d[0:5])=a_list # Obviously this won't work > > ?? > > I am asking this because I have a section of code that contains *lots* > of things like this. It makes the code very unreadable. > > Thanks, > I had a little bit of fun while writing this: itemList = (a,b,c1,c2,c3,d1,d2,d3,d4,d5) and itemList2 = (a1,a2,a3,b,c,d1,d2,d3,d4,d5) the next time. def getSlices(aCount, bCount, cCount, dCount, items): a,b,c,d = (items[0:aCount], items[aCount:aCount+bCount], items[aCount+bCount:aCount+bCount+cCount], item[aCount+bCount+cCount:aCount+bCount+cCount+dCount]) return list(a),list(b),list(c),list(d) >>>a,b,c,d = getSlices(1,1,3,5,itemList) >>>print a,b,c,d ['a'] ['b'] ['c1', 'c2', 'c3'] ['d1', 'd2', 'd3', 'd4', 'd5'] >>>a,b,c,d = getSlices(3,1,1,0,itemList2) >>>print a,b,c,d ['a1', 'a2', 'a3'] ['b'] ['c'] [] %-) Thomas From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Nov 1 10:20:47 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 01 Nov 2006 16:20:47 +0100 Subject: Why can't you assign to a list in a loop without enumerate? References: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> <4qrln8Fo2ollU1@individual.net> Message-ID: <4qrsafFo961qU1@individual.net> Fredrik Lundh wrote: > define "it". Sorry! I mean iterating over a list and having the list index available in the loop. Like: for i, thing in enumerate(things): pass Regards, Bj?rn -- BOFH excuse #254: Interference from lunar radiation From tuomas.vesterinen at pp.inet.fi Sun Nov 5 17:51:00 2006 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Sun, 05 Nov 2006 22:51:00 GMT Subject: forwarding *arg parameter In-Reply-To: References: <6pn3h.125$7b6.98@read3.inet.fi> Message-ID: Dennis Lee Bieber wrote: > On Sun, 05 Nov 2006 17:42:30 GMT, Tuomas > declaimed the following in comp.lang.python: > > > >>I am looking a shorter way to do the above in the case: >> >>def g(*arg): >> return arg >> >>def f(*arg): >> return g(arg) >> >>How can g know if it is called directly with (('foo', 'bar'),) or via f > > > Typically, the responsibility should be on the CALLER, not the > CALLED.. > > >>>>def g(*arg): > > ... return arg > ... > >>>>def f(*arg): > > ... return g(*arg) #<<<<<<<< unpack tuple on call > ... > >>>>f("a", 1, 2) > > ('a', 1, 2) > > > Note how f() is calling g() using an * -- Since f() "knows" that its > arguments were "packed" it calls g() with an unpack marker. Then g() > gets the arguments via whatever scheme it was coded to use. > > >>>>def f(*arg): > > ... return g(arg) #<<<<<<<<<< no tuple unpack > ... > >>>>f("a", 1, 2) > > (('a', 1, 2),) > > I fylly agree with tis: "Typically, the responsibility should be on the CALLER, not the CALLED..". I just don't know how to unpack *arg for calling g. I can get the len(arg), but how to formulate an unpacked call g(arg[0], arg[1], ..). Building a string for eval("g(arg[0], arg[1], ..)") seems glumsy to me. TV From privat at christianhahn.de Fri Nov 10 05:40:10 2006 From: privat at christianhahn.de (ChristianHahn) Date: 10 Nov 2006 02:40:10 -0800 Subject: pythoncom and dialog Message-ID: <1163155210.314431.134980@i42g2000cwa.googlegroups.com> Hi, I inherited a piece of code, that doesn't work anymore. It's a COM-object. One interface method opens a modal dialog ( OpenDialog() ), with the other methods one can set the values for a ComboBox or query the input of the user. This COM-module is istantiated(?) via st=win32com.client.Dispatch(..) within a windows application (btw it's called Prime Front Arena). The scripting language for this application is Python. The COM module works fine, when I call it from Excel via VBA or from python directly. When I call it from the mentioned application, sometime (not always) the python statement st.OpenDialog() never returns and the application is not responding anymore. In the previous release of this appication this piece of code worked. In the new release the app now using two threads, one thread for a log-windows and one thread for all other windows. I don't know if this a problem with pythoncom or a windows problem (two threads, modal dialog), but when I debug it seems to me that it get stuck somewhere in the pythoncom.dll So 1) Does anyone have any hints for. I'm completly in the dark. 2) How can I compile a debug version of the pythoncom.dll by myself? I downloaded the Zip-File, but when I try to open an *.dsp file, i get asked for password (SafeSource)? What's that. You see my windows skill are limited (but increased dramatically the last days). Thanks in advance Christian From rNOSPAMon at flownet.com Thu Nov 30 20:00:38 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 30 Nov 2006 17:00:38 -0800 Subject: Is there a reason not to do this? References: <4t96ujF134nv7U1@mid.uni-berlin.de> Message-ID: In article <4t96ujF134nv7U1 at mid.uni-berlin.de>, "Diez B. Roggisch" wrote: > Ron Garret schrieb: > > One of the things I find annoying about Python is that when you make a > > change to a method definition that change is not reflected in existing > > instances of a class (because you're really defining a new class when > > you reload a class definition, not actually redefining it). So I came > > up with this programming style: > > > > def defmethod(cls): > > return lambda (func): type.__setattr__(cls, func.func_name, func) > > > > class c1(object): pass > > > > @defmethod(c1) > > def m1(self, x): ... > > > > > > Now if you redefine m1, existing instances of c1 will see the change. > > > > My question is: is there a reason not to do this? Does it screw > > something up behind the scenes? Is it unpythonic? Why isn't this > > standard operating procedure? > > What are you doing that needs this permanent redefinition? I like the > repl, yet usually - especially when dealing with classes - I write a > text file containing code. So, i just run that on a command line again, > if I made some changes, recreating whatever objects I want again. > > Even if I'd not do that, but used a long-running interpreter inside an > IDE (which is what I presume you are doing) - why do you _care_ about > the old objects the first place? I mean, you obviously changed the > classes for a reason. So, you are not being productive here, but still > programming. Which means that you don't _have_ to care about old, > unchanged objects too much. > > But in the end - it's your code. It will run slower, it looks kinda > weird as someone who's reading it has to know what it is for, but if it > suits your needs - do it. > > Diez I have two motivations. First, I'm dealing with some classes whose instances take a long time to construct, which makes for a long debug cycle if I have to reconstruct them after every code change. Second, the design just naturally seems to break down that way. I have a library that adds functionality (persistence) to a set of existing classes. The persistence code stores the objects in a relational DB, so it's pretty hairy code, and it has nothing to do with the functionality that the classes actually provide. The original classes are useful even with the persistence code, and I'm trying to keep things lightweight. If there's a better way to accomplish all this I'm all ears. rg From david at boddie.org.uk Mon Nov 6 11:39:06 2006 From: david at boddie.org.uk (David Boddie) Date: 6 Nov 2006 08:39:06 -0800 Subject: ANN: PyQt v4.1 Released References: <1162749608.733730.321970@k70g2000cwa.googlegroups.com> <1162817233.695765.22780@b28g2000cwb.googlegroups.com> Message-ID: <1162831146.195927.296110@e3g2000cwe.googlegroups.com> Tool69 wrote: > I followed the docs to build qscintilla2, all is going well with no > errors, but when I launched the PyQt Syntax Highlighter Example, > nothing is highlighted but the first line of text, whereas the C++ > sample works well in the demo. Do you mean the example from the PyQt4 distribution? That uses a port of an old syntax highlighting example from Qt 4.0. Someone needs to "port" the C++ example from Qt 4.2 to PyQt4. The example itself doesn't actually use QScintilla2 - there used to be a demo from Qt that was converted to use QScintilla. Maybe that's been ported to PyQt as well. David From brian at rkspeed-rugby.dk Fri Nov 3 02:03:52 2006 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: Fri, 03 Nov 2006 06:03:52 -0100 Subject: emacs shell hangs on W32 with python References: <1162508249.399337.233170@m73g2000cwd.googlegroups.com> Message-ID: emin.shopper at gmail.com writes: > Is there any way to run python through emacs or xemacs without having > it hang or is shell support broken? Doing it from eshell gives the same problem :-( -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html Rugbyklubben Speed Scandinavian Open 7s Rugby http://www.rkspeed.dk From sjmachin at lexicon.net Wed Nov 22 17:40:59 2006 From: sjmachin at lexicon.net (John Machin) Date: 22 Nov 2006 14:40:59 -0800 Subject: utf - string translation In-Reply-To: <4564dd7b$0$1349$834e42db@reader.greatnowhere.com> References: <1164224962.711265.198090@h48g2000cwc.googlegroups.com> <1164226304.119425.206380@h54g2000cwb.googlegroups.com> <1164232741.215312.322990@k70g2000cwa.googlegroups.com> <4564dd7b$0$1349$834e42db@reader.greatnowhere.com> Message-ID: <1164235259.737620.323260@m73g2000cwd.googlegroups.com> David H Wild wrote: > In article <1164232741.215312.322990 at k70g2000cwa.googlegroups.com>, > John Machin wrote: > > So why do you want to strip off accents? The history of communication > > has several examples of significant difference in meaning caused by > > minute differences in punctuation or accents including one of which you > > may have heard: a will that could be read (in part) as either "a chacun > > d'eux million francs" or "a chacun deux million francs" with the > > remainder to a 3rd party. > > The difference there, though, is a punctuation character, not an accent. > I did say "differences in punctuation or accents". Yes, the only example I could recall OTTOMH was a difference in punctuation -- according to legend, a fly-spot IIRC :-) From amitsoni.1984 at gmail.com Wed Nov 8 07:35:13 2006 From: amitsoni.1984 at gmail.com (amitsoni.1984 at gmail.com) Date: 8 Nov 2006 04:35:13 -0800 Subject: assigning a sequence to an array In-Reply-To: References: <1162971378.536088.35590@m73g2000cwd.googlegroups.com> Message-ID: <1162989312.966486.272140@m7g2000cwm.googlegroups.com> actually what i want to do is this: i have a file with following format: 1 2 3 9 2 3 4 4 I want to read it and then store the values into two matrices, s.t. A=[1 2;3 9] B=[2 3;4 4] any easier way of doing this? thanks Amit Robert Kern wrote: > amitsoni.1984 at gmail.com wrote: > > Hi, > > I am using "A[a,:]=row" in python, where A is a matrix and row is a > > sequence. But it gives following error: > > -------- error------ > > A[a,:]=row > > ValueError: setting an array element with a sequence. > > > > Is there a way to change type of sequence to array so that this > > situation could be handled > > You don't say what array package you are using. I presume numpy. In any case, > the place to ask those questions (even for the older numarray and Numeric > packages) is the numpy list. > > http://www.scipy.org/Mailing_Lists > > We will need some more information from you when you come to the numpy list. > Please reduce your problematic code to the smallest, self-contained script that > demonstrates the problem, and post it and the exact output that you get. > > -- > 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 fredrik at pythonware.com Sat Nov 11 18:57:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Nov 2006 00:57:23 +0100 Subject: reduce to be removed? In-Reply-To: <1163288885.884417.218270@f16g2000cwb.googlegroups.com> References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163288885.884417.218270@f16g2000cwb.googlegroups.com> Message-ID: Dustan wrote: > Because I'm embedding this expression in a list comprehension because? From elderic at ish.de Thu Nov 2 09:40:31 2006 From: elderic at ish.de (elderic) Date: 2 Nov 2006 06:40:31 -0800 Subject: other ways to check for ? References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> <1162477269.980535.202320@h48g2000cwc.googlegroups.com> Message-ID: <1162478431.624590.29290@m7g2000cwm.googlegroups.com> > What's the problem with this? > > from types import FunctionType > if isinstance(f, FunctionType): > ... > > Bye, > bearophile Well... it's discouraged by the docs =) At least the use of module types. I was just wondering if there were some alternatives. Never thought I would start off a thread this long =) That was basically my reason for asking about something similar like the functions list(), dict(), int(), etc... when called without (), they return . I just wanted to know if there was a keyword for functions, too. Then u could've done: type(f) is function quite similar to: type(x) is int Didn't intent to be a Documentation-Nazi *G* -elderic Excuse my large paste from the Python 2.5 Documentation: --------------------------------------------------------------------------------------- 5.15 types -- Names for built-in types Typical use is for functions that do different things depending on their argument types, like the following: from types import * def delete(mylist, item): if type(item) is IntType: del mylist[item] else: mylist.remove(item) Starting in Python 2.2, built-in factory functions such as int() and str() are also names for the corresponding types. This is now the preferred way to access the type instead of using the types module. Accordingly, the example above should be written as follows: def delete(mylist, item): if isinstance(item, int): del mylist[item] else: mylist.remove(item) --------------------------------------------------------------------------------------- From fsenkel at lynx.neu.edu Mon Nov 6 13:08:47 2006 From: fsenkel at lynx.neu.edu (monkeyboy) Date: 6 Nov 2006 10:08:47 -0800 Subject: Plot pkg - Multiple Y axes? Message-ID: <1162836527.115500.46420@i42g2000cwa.googlegroups.com> Hello, I'm searching for a plotting package that will allow multiple y axes of different scales. For example I'd like to overlay 4 or 5 time series with each series having a separate axis. Does anyone know of such a package? Thank you, Frank From kw at codebykevin.com Sun Nov 26 15:50:43 2006 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 26 Nov 2006 15:50:43 -0500 Subject: Several entries on Tile and TableList at the Tkinter wiki Message-ID: <942ad$4569fe23$4275d90a$25231@FUSE.NET> I'm not sure how often members of this list visit the Tkinter wiki at http://tkinter.unpythonic.net/wiki/FrontPage; this wiki seems to have less traffic in general than the Tcl/Tk wiki at http://wiki.tcl.tk. Given that, I hope it's not out of line for me to call attention to several pages that I've posted about integrating Tile (http://tktable.sourceforge.net/tile) and TableList (http://www.nemethi.de, http://wiki.tcl.tk/5527) into Tkinter applications. I've noted a serious lack of resources/documentation about these two powerful Tk components. In addition to some documentation, screenshots, and sample applications, I've posted updated versions of the original TableList and Tile wrappers by Martin Franklin. I should take this moment to thank Mr. Franklin for his work on these wrappers; whatever I added to them was pretty minimal compared to the heavy lifting he did. He originally posted them on the Internet last year, but the site that hosted them has gone dark. Anyway, Mr. Franklin, if you are reading this, thank you for your hard work; it has been enormously helpful. I hope my own efforts extend your work and make it even more useful for other Tkinter developers. Here are the links: http://tkinter.unpythonic.net/wiki/UsingTile http://tkinter.unpythonic.net/wiki/TileWrapper http://tkinter.unpythonic.net/wiki/TableListWrapper http://tkinter.unpythonic.net/wiki/TableListTileWrapper http://tkinter.unpythonic.net/wiki/PyLocateTile http://tkinter.unpythonic.net/wiki/PyLocate Hope these prove useful to others, as starting points for your own work if nothing else. Corrections and improvements are of course invited; it's a wiki! -- Kevin Walzer Code by Kevin http://www.codebykevin.com From nateastle at gmail.com Sat Nov 18 11:50:56 2006 From: nateastle at gmail.com (nateastle at gmail.com) Date: 18 Nov 2006 08:50:56 -0800 Subject: basic python questions In-Reply-To: References: <1163829271.660193.70450@j44g2000cwa.googlegroups.com> Message-ID: <1163868656.416276.277310@m7g2000cwm.googlegroups.com> I have taken the coments and think I have implemented most. My only question is how to use the enumerator. Here is what I did, I have tried a couple of things but was unable to figure out how to get the line number. def Xref(filename): try: fp = open(filename, "r") except: raise "Couldn't read input file \"%s\"" % filename dict = {} line_num=0 for words in iter(fp.readline,""): words = set(words.split()) line_num = line_num+1 for word in words: word = word.strip(".,!?:;") if not dict.has_key(word): dict[word] = [] dict[word].append(line_num) fp.close() keys = sorted(dict); for key in keys: print key," : ", dict[key] return dict Marc 'BlackJack' Rintsch wrote: > In <1163829271.660193.70450 at j44g2000cwa.googlegroups.com>, > nateastle at gmail.com wrote: > > > def Xref(filename): > > try: > > fp = open(filename, "r") > > lines = fp.readlines() > > fp.close() > > except: > > raise "Couldn't read input file \"%s\"" % filename > > dict = {} > > for line_num in xrange(len(lines)): > > Instead of reading the file completely into a list you can iterate over > the (open) file object and the `enumerate()` function can be used to get > an index number for each line. > > > if lines[line_num] == "": continue > > Take a look at the lines you've read and you'll see why the ``continue`` > is never executed. > > > words = lines[line_num].split() > > for word in words: > > if not dict.has_key(word): > > dict[word] = [] > > if line_num+1 not in dict[word]: > > dict[word].append(line_num+1) > > Instead of dealing with words that appear more than once in a line you may > use a `set()` to remove duplicates before entering the loop. > > Ciao, > Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Mon Nov 20 14:23:45 2006 From: sjmachin at lexicon.net (John Machin) Date: 20 Nov 2006 11:23:45 -0800 Subject: Help!!! New to Python and getting an error I can't figure out References: Message-ID: <1164050624.217296.267630@k70g2000cwa.googlegroups.com> Tom Mountney wrote: > Any help is greatly appreciated!!! > > I'm learning python and from a book I tried this program: (all the > indentation is there just doen't appear in this EMail) Some books have websites from which you can download the source of examples so you don't have to type them in carefully yourself; is this one not so? > ---------------------------------------------------------- > [snip] > def findfiles(self, pattern): > "Accepts pattern, returns filenames that contain pattern" > return[x for x in self.files if x.find(pattern) != -1 You are missing a bracket ("]") off the end of this line. Python allows automatic statement continuation while there are excess left parentheses brackets & braces, so you don't get told about the error until the next line. BTW, most modern text editors and IDEs have some sort of assistance with ()[]{} > > #test > if __name__ == "__main__": > (g = dirGrep("c:\\winnt")) > files = g.findFiles(".py") > print g.findLines("java", files) > > When I try to run the program - python grep.py - I get the following error: > > C:\> python grep.py > File "grep.py", line 28 > if __name__ == '__main__': > ^ > SyntaxError: invalid syntax > > What am I doing wrong? > Thanks for any help HTH, John From acatejr at gmail.com Tue Nov 21 00:59:49 2006 From: acatejr at gmail.com (acatejr at gmail.com) Date: 20 Nov 2006 21:59:49 -0800 Subject: Parsing/Splitting Line Message-ID: <1164088789.316244.124340@b28g2000cwb.googlegroups.com> I have a text file and each line is a list of values. The values are not delimited, but every four characters is a value. How do I get python to split this kind of data? Thanks. From rjtucke at gmail.com Wed Nov 29 23:40:22 2006 From: rjtucke at gmail.com (rjtucke) Date: 29 Nov 2006 20:40:22 -0800 Subject: a quickie: range - x In-Reply-To: <1164858136.495250.180790@14g2000cws.googlegroups.com> References: <1164858136.495250.180790@14g2000cws.googlegroups.com> Message-ID: <1164861622.129857.176190@h54g2000cwb.googlegroups.com> Thanks, all- that helped. Ross From no-spam at no-spam-no-spam.com Thu Nov 2 13:10:42 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 02 Nov 2006 19:10:42 +0100 Subject: Python in sci/tech applications In-Reply-To: <1162489638.013433.102180@h48g2000cwc.googlegroups.com> References: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> <1162489638.013433.102180@h48g2000cwc.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > mattf: >> 3) -There's a problem with development under Windows. > > It's possibile to compile Python with MinGW, and to create extensions > with it. So some site can host a single zip file that contains both > MinGW and Python compiled with it, all ready and set. A person not much > expert can then create compiled small extensions in a short time > without too much complexities. (Or maybe the D language can be packed > into that, instead of MinGW, to do similar things. D can be a good > language used with Python) But then probably PIL, scipy, etc have to be > compiled again for such alternative official or semi-official Python > distribution. > Is it really not possible to create extension libs with older MSVC or Mingw, which work with regular Python binaries version 2.4 and 2.5 ? Maybe with some special import libraries? (another option is to stay with Python2.3, which has a small memory footprint and compiles with crtl4.2 libs (VC6, ...) ) -robert From cliff at develix.com Wed Nov 8 15:00:28 2006 From: cliff at develix.com (Cliff Wells) Date: Wed, 08 Nov 2006 12:00:28 -0800 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> Message-ID: <1163016028.3371.60.camel@localhost.localdomain> On Wed, 2006-11-08 at 11:18 -0800, Aahz wrote: > In article , > wrote: > > > >I'm with Beliavsky on this one. I can't see any particular reason to curse > >in a forum such as c.l.py. It just coarsens the discussion with no obvious > >positive benefit as far as I can see. > > Actually, I do agree that profanity "should" be avoided on c.l.py; what > I disagree with rather vociferously is having language police like > Beliavsky. I consider Beliavsky's offense far worse than the original > post. I think this sums up my point of view as well (although I would have used around 3215 more words to say it). Cliff From uche.ogbuji at gmail.com Sun Nov 19 08:03:41 2006 From: uche.ogbuji at gmail.com (Uche Ogbuji) Date: 19 Nov 2006 05:03:41 -0800 Subject: lxml/ElementTree and .tail In-Reply-To: References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> <761846B7-E374-41FE-8804-CBB3D42FD4D2@snowtide.com> <1163835505.102190.140060@b28g2000cwb.googlegroups.com> Message-ID: <1163941421.235619.150260@f16g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Uche Ogbuji wrote: > > > I certainly have never liked the aspects of the ElementTree API under > > present discussion. But that's not as important as the fact that I > > think the above statement is misleading. There has always been a > > battle in XML between the people who think the serialization is > > preeminent, and those who believe some data model is preeminent, but > > the reality is that XML 1.0 (an 1.1) is a spec *defined* by its > > serialization. > > sure, the computing world is and has always been full of people who want > the simplest thing to look a lot harder than it actually is. after all, > *they* spent lots of time reading all the specifications, they've bought > all the books, and went to all the seminars, so it's simply not fair > when others are cheating. You sound bitter about something. Don't worry, it's really not all that serious. > in reality, *all* interchange formats are easier to understand and use > if you focus on a (complete or intentionally simplified) data model of > the things being interchanged, and treat various artifacts of the > byte-stream used by the wire format as artifacts, historical accidents > based on what specification happened to be written before the other, or > what some guy did or did not do in the seventies, as accidents, and > esoteric arcana disseminated on limited-distribution mailing lists as > about as relevant for your customer as last week's episode of American Idol. The fact that the XML Infoset is hardly used outside W3C XML Schema, and that the XPath data model is far more common, and that focus on the serialization is even more common than that is a matter of everyday practicality. And oh by the way, this thread is all about *your* customer's complaining. And your response is to give them your philosophical take on XML. Doesn't that contradict what you're saying above? Oh never mind. You posted something misleading, and I posted another point of view. I know you're incapable of any disagreement that doesn't devolve into a full-scale flame-war. Sometimes I have time for that sort of thing. This is not one fo those times, so this is probably where I get off. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From steve at holdenweb.com Fri Nov 10 15:42:29 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Nov 2006 14:42:29 -0600 Subject: Modules, Packages and Developer Confusion. Oh My! In-Reply-To: <1163190657.792705.55030@m73g2000cwd.googlegroups.com> References: <1163190657.792705.55030@m73g2000cwd.googlegroups.com> Message-ID: dhable at gmail.com wrote: > I think I'm still missing something in how python is handling packages > and it's mixing me up. I have a package with three files (modules?) > like so: > > OPS:\ > __init__.py > model.py > search.py > > To hide more details of the package structure, I import model and > search inside of __init__. It also seemed like a good idea to define a > global function that creates a database connection and I added it to > __init__.py. Thus, I have: > > > from model import * > from search import * > > def create_connection(): > # details are unimportant for this example > > > When I try to use the create_connection function in model, I get errors > when I use it as a global function ( just create_connection()). The > only way to resolve the error was to import OPS inside of model and use > OPS.create_connection(). This doesn't seem natural. If model is part of > OPS, why do I need to tell python to import OPS and use this function > from OPS? I can see doing that from the outside world, but inside? > > Any clarification would be greatly appreciated. > The def statement binds the name create_connection in the model module's namespace to the function it defines. So you write EITHER import model # puts model in the current namespace conn = model.create_connection( ... ) OR from model import * # copies model's namespace into current conn = create_connection( ... ) Hope this helps. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jstroud at mbi.ucla.edu Fri Nov 3 23:50:22 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 04 Nov 2006 04:50:22 GMT Subject: Python Classes and dynamic class members In-Reply-To: <1162597703.632080.75970@i42g2000cwa.googlegroups.com> References: <1162596614.073100.54850@e3g2000cwe.googlegroups.com> <1162597703.632080.75970@i42g2000cwa.googlegroups.com> Message-ID: acatejr at gmail.com wrote: > James Stroud wrote: > >>acatejr at gmail.com wrote: >> >>>I have a text file that I am parsing. Each line is of the form: >>> >>>max_time 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10 0.11 0.12 >>> >>>The first item is the field name and the next twelve items are values >>>for each month in the year. There are multiple lines each for some >>>different variable. I am able to parse this data easily enough, but >>>what I'd like to do is have a class that stores all this infomormation >>>using dynamic member attributes/fields and the resulting list of >>>values. For example, if the class WeatherData was instantiated and I >>>parsed the line above as so: >>> >>>field_name = "max_time; >>>values = [0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.10,0.11,0.12] >>> >>>how could I get weather data to store values in an attribute called >>>"max_time"? Ultimately, something like this would be possible: >>> >>> >>> >>>>>>WeatherData.max_time >>>>>>[0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.10,0.11,0.12] >>> >>> >>>Any help would be appreciated. >>> >> >>setattr(Weatherdata, "max_time", max_time) >> > Thanks a lot!! > > I did find that creating and calling the following method works too: > > def setAt(self, field, data): > expression = "self." + field + " = data" > exec(expression) > > I just don't know which one would be more efficient, but I like setattr > better. > You have good taste. You probably want to steer away from exec() if you ever have the inclination. Python usually has an "approved", or pythonic, way of solving problems you may want to address with exec(). James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bdesth.quelquechose at free.quelquepart.fr Thu Nov 2 16:07:49 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 02 Nov 2006 22:07:49 +0100 Subject: is mod_python borked? In-Reply-To: References: Message-ID: <454a597f$0$3721$426a74cc@news.free.fr> Michael S a ?crit : > I used it for various projects. It's alright. > The only problem I had, was that I was unable to get > mod_python and pysqlite to work together. Seems there's a strange bug with pysqlite when you have both mod_python/pysqlite and php5... From antroy at gmail.com Sat Nov 25 14:48:45 2006 From: antroy at gmail.com (Ant) Date: 25 Nov 2006 11:48:45 -0800 Subject: Invoking Python from Cygwin problem. In-Reply-To: <1164473686_17679@sp6iad.superfeed.net> References: <1164385876.755749.139020@l39g2000cwd.googlegroups.com> <1164473686_17679@sp6iad.superfeed.net> Message-ID: <1164484125.600450.236090@14g2000cws.googlegroups.com> Cousin Stanley wrote: ... > Using Cygwin and Python 2.4 under Win2K the following version > of your code seems to work OK here with no extraneous CR .... Hmm. Just tried it here at home (Python 2.5) and it works fine as well... Cygwin was pre-installed on my machine when I started work at the new job a couple of weeks ago. I wonder if it's an old version they had installed. I'll try updating Cygwin at work and see what happens... From sjdevnull at yahoo.com Thu Nov 9 16:00:27 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 9 Nov 2006 13:00:27 -0800 Subject: [OT] Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <1163092617.499298.326930@f16g2000cwb.googlegroups.com> Message-ID: <1163106027.285495.135550@i42g2000cwa.googlegroups.com> Steve Holden wrote: > Paul Boddie wrote: > > Steve Holden wrote: > >> Paul Boddie wrote: > >>> http://www.python.org/doc/faq/general/#why-are-colons-required-for-the-if-while-def-class-statements > >>> > >> I suppose it would be even better if that hyperlink actually took you to > >> section 1.4.27 rather than 1.4.14 ... > > > > I'd suggest a browser upgrade: even the old version of Konqueror I'm > > using here manages to scroll to the right place. And it isn't a Web > > site maintenance problem, either, although I did have my suspicions. > > > YTes, IE copes with it but Firefox doesn't. Having heard a number of > complaints about Firefox 2 I'm tempted to stick with 1.5.0.8 just a > little longer. FWIW, Firefox 2.0 and 1.5.0.7 both work properly on this link (as does Epiphany 1.2.10). Linux 2.6-based system. From larry.bates at websafe.com Mon Nov 6 17:03:31 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 06 Nov 2006 16:03:31 -0600 Subject: auto indent In-Reply-To: References: Message-ID: <454FB133.5020708@websafe.com> M.N.Smadi wrote: > Hi there; > > i have a script that is not indented properly. Is there a way that i can > have it auto indented. > > thanks > moe smadi Not really. Indention in python conveys blocks so there is no way anything automatic could determine where blocks end. Its just like asking if you could have something automatically insert parenthesis everywhere they are needed. -Larry From johnjsal at NOSPAMgmail.com Tue Nov 7 09:45:40 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 07 Nov 2006 09:45:40 -0500 Subject: sqlite error? In-Reply-To: <1162876815.281902.70620@e3g2000cwe.googlegroups.com> References: <454fa4dc$0$6987$c3e8da3@news.astraweb.com> <1162849478.092439.297160@i42g2000cwa.googlegroups.com> <454faf0a$0$12993$c3e8da3@news.astraweb.com> <1162876815.281902.70620@e3g2000cwe.googlegroups.com> Message-ID: <45509c05$0$26457$c3e8da3@news.astraweb.com> Frank Millman wrote: > Definitely not. You could have a sql command like this - > > cur.execute("UPDATE table SET col1 = ?, col2 = ? WHERE col3 = ? AND > col4 = ?",(1,2,3,4)) > > The parameters could be scattered throughout the command. Therefore the > substitution is one-for-one from left to right using the values in the > tuple. > Thanks! The example I was looking at in the docs didn't use parentheses, but I also didn't connect that with the fact that it was only using a one-tuple! :) From carsten at uniqsys.com Mon Nov 27 14:41:24 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 27 Nov 2006 14:41:24 -0500 Subject: Inheritance from builtin list and override of methods. In-Reply-To: References: <200611261804.54669.mgiann@beta-cae.gr> <200611271133.48359.mgiann@beta-cae.gr> Message-ID: <1164656484.3361.15.camel@dot.uniqsys.com> On Mon, 2006-11-27 at 19:14 +0000, OKB (not okblacke) wrote: > Duncan Booth wrote: > > >> And is there a mechanism in Python that will allow me to override > >> the operators of a class, for all its occurrences, even the ones > >> implemented on C built-in objects? > > > > No. > > For what it's worth, which is undoubtedly nothing, Correct. > this is > something that I think needs to change. All this talk about new-style > classes and class-type unification is empty words if you can't override > anything on any type without having to know whether it's written in C or > Python. Duncan's "No" response was not referring to overriding in general, it was referring to the OP's original question which amounted to "Can I affect the behavior of method Z by overriding methods X and Y". The inability to influence a method by overriding completely different methods has nothing to do with whether that method is implemented in C or Python; it has to with whether the method in question calls the overridden methods, and in general it won't. You can change the behavior of a list's sort method by overriding sort. You can't change the behavior of sort by overriding __getitem__ and __setitem__, because sort does not call __getitem__ or __setitem__. Hope this helps, Carsten. From chris.van.bael at gmail.com Wed Nov 8 06:24:33 2006 From: chris.van.bael at gmail.com (Chris_147) Date: 8 Nov 2006 03:24:33 -0800 Subject: Python deployment options. References: <1162982262.010438.99260@f16g2000cwb.googlegroups.com> Message-ID: <1162985073.163257.110180@m73g2000cwd.googlegroups.com> king kikapu wrote: > Hi to all folks here, > > i just bought a book and started reading about this language. > I want to ask what options do we have to deploy a python program to > users that do not have the labguage installed ?? > > I mean, can i make an executable file, or something that contains the > runtime and the modules that the program only use or am i forced to > download the language to the user machine so the .py files can be run > ?? > > Thanks in advance, > > king kikapu Well, on Windows you have to look for the Py2Exe package (www.py2exe.org) On Mac OS X you can use Py2App (http://undefined.org/python/py2app.html) Mind you, on Windows there is one big potentional problem: Python is compiled with Visual Studio 2003 and needs msvcr71.dll. So Py2Exe wants to distribute that dll also, but if you don't have a valid Visual Studio license, you are not allowed to. It is explained further in this thread: http://groups.google.com/group/comp.lang.python/browse_frm/thread/bccb45b7dae7ddd5/dacec12e300a74d4#dacec12e300a74d4 I doubt Microsoft will unleash their lawyers on you, but it is a problem. From NikitaTheSpider at gmail.com Wed Nov 29 15:55:57 2006 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Wed, 29 Nov 2006 20:55:57 GMT Subject: Good script editor for Python on Mac OS 10.3 References: <1164830360.213197.182560@l12g2000cwl.googlegroups.com> Message-ID: In article , Lou Pecora wrote: > In article <1164830360.213197.182560 at l12g2000cwl.googlegroups.com>, > "Scott_Davies" wrote: > > > Hi, > > > > I have an old Mac with OS X Panther installed. I also have the Python > > language download file, but I haven't got a text/script editor to use > > for it. Does anyone have a recommendation for a good Python text > > editor in OS 10.3? > > > > Thanks, > > > > Scott D. > > > > Try TextWrangler. It's free. I use it's big brother BBEdit and like it. I second that recommendation. -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From steve at rueb.com Wed Nov 29 18:35:39 2006 From: steve at rueb.com (Steve Bergman) Date: 29 Nov 2006 15:35:39 -0800 Subject: Remarkable results with psyco and sieve of Eratosthenes In-Reply-To: <456e08ba$0$1505$db0fefd9@news.zen.co.uk> References: <1164837289.295731.178070@h54g2000cwb.googlegroups.com> <456e08ba$0$1505$db0fefd9@news.zen.co.uk> Message-ID: <1164843339.129776.110420@j72g2000cwa.googlegroups.com> Will McGugan wrote: > Some trivial optimizations. Give this a whirl. I retimed and got 9.7 average for 3 runs on my version. Yours got it down to 9.2. 5% improvement. Not bad. (Inserting '2' at the beginning doesn't seem to impact performance much.;-) ) BTW, strictly speaking, shouldn't I be adding something to the floating point sqrt result, before converting to int, to allow for rounding error? If it is supposed to be 367 but comes in at 366.99999999, don't I potentially classify a composite as a prime? How much needs to be added? From fredrik at pythonware.com Wed Nov 22 13:45:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Nov 2006 19:45:41 +0100 Subject: KeyboardInterrupt from syscalls In-Reply-To: <1164220772.5961.53.camel@pc7.dolda2000.com> References: <1164220772.5961.53.camel@pc7.dolda2000.com> Message-ID: Fredrik Tolf wrote: > So how does it work? Does my code get to return Py_FALSE, and the > interpreter ignores it, seeing that an exception is set? Is a non-local > exit performed right over my call stack (in which case my next question > would be how to clean up resources being used from my C code)? Or does > something completely else happen? the signal handler adds an entry to a "pending calls" queue, which is checked by the interpreter at regular intervals. From no-spam at no-spam-no-spam.invalid Sun Nov 5 08:43:47 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sun, 05 Nov 2006 14:43:47 +0100 Subject: Trouble compiling win32all on Windows In-Reply-To: <1162687975.665327.107030@m7g2000cwm.googlegroups.com> References: <1162687975.665327.107030@m7g2000cwm.googlegroups.com> Message-ID: Ross Ridge wrote: > robert wrote: >> I've trouble compiling win32all. VC98 and latest SDK installed >> (otherwise with original SDK it won't even compile). >> It tells that uuid.lib(cguid_i.obj) : fatal error LNK1103: debug info >> is destroyed. > > The library isn't compatable with the compiler you're using. You'll > need to use an older version of the Platform SDK that supports your > compiler. thanks. the last Windows SDK supporting VC6 (Py2.3) is February 2003 Edition. If someone seeks here: MS' front pages tell you need to get it via CD. Yet this SDK exists (well hidden) on the net here: http://www.microsoft.com/msdownload/platformsdk/sdkupdate/psdk-full.htm wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.1.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.2.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.3.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.4.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.5.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.6.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.7.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.8.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.9.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.10.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.11.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.12.cab wget http://download.microsoft.com/download/platformsdk/sdk/update/win98mexp/en-us/3790.0/FULL/PSDK-FULL.13.cab one needs to set IE as default browser during installation. otherwise setup.exe will fail. robert From richardjones at optushome.com.au Thu Nov 9 22:03:14 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Fri, 10 Nov 2006 14:03:14 +1100 Subject: Registrations are open for tutorials at OSDC 2006 Message-ID: <200611101403.14997.richardjones@optushome.com.au> Time is running out to register for tutorials at the Open Source Developers' Conference 2006 tutorial program: http://www.osdc.com.au/registration/index.html The tutorials run on the 5th December, followed by the technical program on the 6th - 8th December. Most tutorials include printed reference material. Our tutorial program is included below: Room 1 Room 2 9:00am Cascading Style Sheets Open Source Python GIS Hacks 12:30pm Lunch Lunch 1:30pm Test Web Apps with Perl Drupal Tutorial 3:00pm Afternoon tea Afternoon tea 3:30pm Intro to Perl Template::Toolkit Large Scale Web Apps A morning tea break will occur roughly half way through the the 9am - 12:30pm tutorials. For more information on what each tutorial covers, please visit: http://www.osdc.com.au/papers/tutorials.html Prices and information on how to register can be found at: http://www.osdc.com.au/registration/index.html You can help us make this conference be the best developers' conference this year just by turning up and participating! We look forward to sharing this great conference with you. If your business would like to benefit from exposure to many of Australia's best open source developers then perhaps you should consider sponsorship. We have a wide range of sponsorship options, to find out more information please visit: http://www.osdc.com.au/sponsors/index.html Richard Jones OSDC Program Chair From claird at lairds.us Wed Nov 15 21:41:34 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 16 Nov 2006 02:41:34 +0000 Subject: Python v PHP: fair comparison? References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> Message-ID: In article <1163559359.010787.185840 at m73g2000cwd.googlegroups.com>, Luis M. Gonz?lez wrote: . . . >Then look no further. Learn python and go kick php developers asses in >the market place. >There are thousands of php developers out there. Do you want to be just >one more? >I'd rather learn something newer, and much more powerful. . [more Python cheerleading] . . Perhaps it's timely to clarify the "newer" above: Guido made Python public in '89-90, and Rasmus showed PHP to others in '94-95. From fredrik at pythonware.com Thu Nov 16 08:08:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 14:08:27 +0100 Subject: Python v PHP: fair comparison? In-Reply-To: <1163681949.338244.323390@k70g2000cwa.googlegroups.com> References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> <1163681949.338244.323390@k70g2000cwa.googlegroups.com> Message-ID: Luis M. Gonz?lez wrote: > But as a web development language, it's olnly when people started to > look for the "rails killer" and many python alternatives started to > come up (although Django has been in development for a long time before > all this hype). nah, people have built web stuff on Python for as long as we've had a web. From craigtw.online at gmail.com Thu Nov 30 22:14:56 2006 From: craigtw.online at gmail.com (Craig) Date: 30 Nov 2006 19:14:56 -0800 Subject: Open 16-bit/24-bit windows bitmap using PIL Message-ID: <1164942896.485414.192320@16g2000cwy.googlegroups.com> Hi there, I'm trying to open a 256-colour windows BMP and a 24-bit windows BMP with PIL usiing the following command: Image.open("image.bmp") When I try and open the 24-bit BMP the error I get is: Traceback (most recent call last): File "", line 1, in im = Image.open("lightbulb.bmp") File "C:\Python25\lib\site-packages\PIL\Image.py", line 1730, in open return factory(fp, filename) File "C:\Python25\lib\site-packages\PIL\ImageFile.py", line 82, in __init__ self._open() File "C:\Python25\lib\site-packages\PIL\BmpImagePlugin.py", line 164, in _open self._bitmap(offset=offset) File "C:\Python25\lib\site-packages\PIL\BmpImagePlugin.py", line 96, in _bitmap raise IOError("Unsupported BMP header type (%d)" % len(s)) IOError: Unsupported BMP header type (108) When I try and open the 256-colour BMP the error I get is: Traceback (most recent call last): File "", line 1, in im = Image.open("lightbulb2.bmp") File "C:\Python25\lib\site-packages\PIL\Image.py", line 1730, in open return factory(fp, filename) File "C:\Python25\lib\site-packages\PIL\ImageFile.py", line 82, in __init__ self._open() File "C:\Python25\lib\site-packages\PIL\BmpImagePlugin.py", line 164, in _open self._bitmap(offset=offset) File "C:\Python25\lib\site-packages\PIL\BmpImagePlugin.py", line 120, in _bitmap raise IOError("Unsupported BMP compression (%d)" % compression) IOError: Unsupported BMP compression (1) I can open a windows monochrome bitmap fine using PIL but the colour options are more desirable. I am using Windows 2000 if that is any help and I am saving the different BMP's using Microsoft Paint. If you could help that would be great. Craig From bignose+hates-spam at benfinney.id.au Thu Nov 2 20:14:09 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 03 Nov 2006 12:14:09 +1100 Subject: other ways to check for ? References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> <1162477269.980535.202320@h48g2000cwc.googlegroups.com> <1162478431.624590.29290@m7g2000cwm.googlegroups.com> <1162484302.234145.245320@e3g2000cwe.googlegroups.com> <1162515037.427613.279250@i42g2000cwa.googlegroups.com> Message-ID: <873b9149i6.fsf@benfinney.id.au> "eduardo.padoan at gmail.com" writes: > Python should have a TypeError subclass: "NotCallableError", to > enforce BAFP. Bureau of Alcohol, Firearms, and Programmers? (Perhaps you meant "EAFP") -- \ "If you go flying back through time and you see somebody else | `\ flying forward into the future, it's probably best to avoid eye | _o__) contact." -- Jack Handey | Ben Finney From john at castleamber.com Thu Nov 16 15:04:22 2006 From: john at castleamber.com (John Bokma) Date: 16 Nov 2006 20:04:22 GMT Subject: Python v PHP: fair comparison? References: Message-ID: "Demel, Jeff" wrote: > What kind of hosting does one get for $10 a *year*? And I'm not just > talking Python here, but any hosting at all. I pay $12/year (see other posts, I am not going to name them again) for hosting a phpBB board and wiki, with 100+ members and currently close to 20,000 posts. Minor issues were fixed within about one hour after emailing the hosting provider. When I had problems with data storage (my fault, I used too much) my 100 MB was extended to 500 MB without additional costs. Haven't seen major issues the one year and half the board is up, everything goes smooth. No idea how a heavy traffic site would go with them though, my personal page with 14k visitors is hosted somewhere else, and I pay much more (maybe even too much atm., I am probably going to move to VPS anyway). But for a message board for friends, paying less then 20 USD/year, is fine with me. One friend has her own board & blog with them, and since hosting comes with cpanel, she didn't need much of my help :-). -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From __peter__ at web.de Thu Nov 2 09:52:25 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Nov 2006 15:52:25 +0100 Subject: __div__ not recognized automatically References: Message-ID: Anton81 wrote: > Hello! > > I wrote a class > > class NumX: > ... > def __add__(self,other): > ... > def __div__(self,other): > if not isinstance(other,NumX): other=NumX(other) > ... > > Somewhere else I use > > a=(b+c)/2 > > where all variables are of NumX Type. When I execute the program it > complains that it can't find an operator "/" for "instance" and "integer". > However if I use pdb the same command works when started on the prompt. > Also the manual execution > > a=(b+c).__div__(2) > > works. Any suggestions what goes wrong? If you have the from __future__ import division statement, you need to override __truediv__(), not __div__() Peter From tzong at sigma-rt.com Wed Nov 29 20:03:18 2006 From: tzong at sigma-rt.com (Tommy Zong) Date: Thu, 30 Nov 2006 09:03:18 +0800 Subject: [help] Is it true to call obj.__str__() while executing "print obj"? Message-ID: <20061130011050.228691E4003@bag.python.org> Hi, I am learning metaclass by reading "Metaclass programming in Python, Part 2". I have a question as following and had tried to search from internet and also have read the article "Unifying types and classes in Python 2.2" but failed to get satisfied answer. Could you please give me any comments to enlighten me? Thank you very much. {{{ # # inheritance inheritance # object -------------> type -------------> Printable(Printable.__str__) # | . # | . instantiation # | . # | v # ----------------------------------------> C(?) # . # . instantiation # . # v # c(?) # >>> class Printable(type): ... def __str__(cls): ... return "This is class %s" % cls.__name__ ... >>> class C(object): ... __metaclass__ = Printable ... >>> print C # equivalent to print Printable.__str__(C) This is class C >>> c = C() >>> print c # equivalent to print C.__str__(c) <__main__.C object at 0x1870dacc> >>> C.__str__ >>> print C This is class C }}} The question is why Printable.__str__ is invoked while executing "print C" but "C.__str__" shows it is resolved as "objct.__str__"? Wish I can get reply from you. Really thanks. Best Regards, Tommy Zong Chengdu Jiehua Technologies Co, Ltd. Tel: 86-28-85148500-654 Mail: tzong at sigma-rt.com MSN: metalzong at 163.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Mon Nov 6 17:21:04 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 06 Nov 2006 19:21:04 -0300 Subject: Projecting MUD maps In-Reply-To: <740c3aec0611051432v4bb92f2gc7fa7a933954f64f@mail.gmail.com > References: <740c3aec0611051432v4bb92f2gc7fa7a933954f64f@mail.gmail.com> Message-ID: <7.0.1.0.0.20061106191847.0493e930@yahoo.com.ar> At Sunday 5/11/2006 19:32, BJ?rn Lindqvist wrote: >Hello, I'm looking for an algorithm to project "MUD maps" such as the >following map: http://www.aww-mud.org/maps/MUD_Maps/Caerin-colour.jpg > >MUD:s consists of rooms, each rooms has up to four orthogonal edges >(north, east, west and south) that connects it to another room. So it >is very easy to model a MUD as a directed graph. But projecting the You could use dot www.graphviz.org I think there is a python wrapper -pydot maybe?- but anyway the dot file format is very easy to write. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From gagsl-py at yahoo.com.ar Thu Nov 2 18:34:16 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 02 Nov 2006 20:34:16 -0300 Subject: scared about refrences... In-Reply-To: <1162506227.070059.230550@h54g2000cwb.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162251429.386255.289620@e3g2000cwe.googlegroups.com> <4547d0d7$0$7246$426a34cc@news.free.fr> <1162412436.595926.66940@i42g2000cwa.googlegroups.com> <454a5672$0$3721$426a74cc@news.free.fr> <1162506227.070059.230550@h54g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061102193336.05c2dd88@yahoo.com.ar> At Thursday 2/11/2006 19:23, SpreadTooThin wrote: >I realize I may be beating a dead horse here... but... > >def fn(x): > x = x + 1 > print x >a = 2 >fn(a) > >>> 3 >print a > >>> 2 > >So in some cases the it is safe to assume that your variables to >function will not >change in other cases it is not.. but they are all the same... Forget about variables! In Python you have objects. Objects don't have a name, but you may use a name to refer to them. In the code above, `a` is not a variable, neither an object; it's just a name referring to an object (a name bound to an object); such object is an instance of type int, with value 2, to be precise. fn(a) calls function fn [in fact, "the object bound to the name fn"] passing an object -the object referenced by the name `a`- as its only argument. Inside function fn, it gets a single argument bound to the name x. You do some math and bind the resulting object to the local name `x`. Now x refers to another instance of type int, with value 3. The original int object is not modified - and never could have been, since int's are immutable, you cant change them (a 2 will always be a 2: if you get a 3, it's ANOTHER object). After function fn finishes, execution continues with the `print a` statement. Nobody has changed the object pointed by the name `a`, so it's still the int with value 2, and that's what you get. All objects have identity. You can test identity using the `is` operator: `a is b` returns True iff both objects are identical (both are "the same object" just being referred by another name). The function id() returns the object identity. Some objects (by example, containers like lists and dicts) are mutable. That means that you can change it's value, but the remain being the same object. By example: --- begin test.py --- def g(x): print 'x[1], in:', x[1] x[1] = 10 print 'x[1], out:', x[1] a1=1 a2=2 a3=3 foo=[a1,a2,a3] print "before, foo=",foo,"id(foo)=",id(foo) print "a2=",a2,"id(a2)=",id(a2) g(foo) print "after, foo=",foo,"id(foo)=",id(foo) print "a2=",a2,"id(a2)=",id(a2) --- end test.py --- Output: before, foo= [1, 2, 3] id(foo)= 12350728 a2= 2 id(a2)= 11163404 x[1], in: 2 x[1], out: 10 after, foo= [1, 10, 3] id(foo)= 12350728 a2= 2 id(a2)= 11163404 Function g modifies the second "slot" in the list - it does not modify the object already in that place, it just makes the second item in the list to refer to another object (the int 10). The previous reference (the int 2) is lost. Anyway, the list remains "the same" (look at id(foo)). The name a2 still refers to the int 2 (because nobody changed that). It's really easy once you get it - and then, just enjoy writing Python code! -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From no-spam at no-spam-no-spam.invalid Sat Nov 4 07:44:09 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sat, 04 Nov 2006 13:44:09 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <454bd36c$0$2364$9b622d9e@news.freenet.de> References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <454bd36c$0$2364$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > robert schrieb: >> in combination with some simple locking (anyway necessary) I don't see a >> problem in ref-counting. > > In the current implementation, simple locking isn't necessary. > The refcounter can be modified freely since the code modifying > it will always hold the GIL. ( meant: a lock to prevent multiple Interpreters accessing concurrently the hot shared/tunneled objects ) >> ---- Question Besides: do concurrent INC/DEC machine OP-commands >> execute atomically on Multi-Cores as they do in Single-Core threads? > > Not necessarily, no. On x86, you need to prefix the instruction > with the LOCK prefix for it to become atomic. Otherwise, the > two necessary read/write cycles to main memory may interleave > with the memory operations of another processor. > > On other processors, INC might not exist at all as an > instruction; when you only have register add, then implementing > an atomic increment is a challenge. That's why the Windows API > provides you with an atomic increment function as part of the > operating system API. Thanks for that info. That is interesting. Thus even on x86 currently this LOCK is not used (just (op)->ob_refcnt++) ) Reading this I got pinched: In win32ui there are infact Py_INC/DECREF's outside of the GIL ! And I have a severe crash problem with threaded apps - the problem is only only on dual cores ! That pointer probably will end a long search... robert PS: Besides: what are speed costs of LOCK INC ? From john106henry at hotmail.com Thu Nov 9 15:06:47 2006 From: john106henry at hotmail.com (John Henry) Date: 9 Nov 2006 12:06:47 -0800 Subject: How to choose the right GUI toolkit ? In-Reply-To: <1163092380.301382.113470@m7g2000cwm.googlegroups.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163092380.301382.113470@m7g2000cwm.googlegroups.com> Message-ID: <1163102807.741768.195310@m73g2000cwd.googlegroups.com> Dan Lenski wrote: > > John H.: thanks for pointing out pythoncard. This looks like it might > be an excellent substitute for LabView-like GUIs, which all my > coworkers like. I personally refuse to read or write LabView code, on > the grounds that its syntax causes severe brain damage and is > completely unportable. But that's a flame for another thread, so to > speak... > > Thanks, > Dan I assume you meant that the example programs looks LabView-like GUIs? PythonCard itself has nothing in common with LabView. It's more like HyperCard. From nirnimesh at gmail.com Thu Nov 2 07:52:05 2006 From: nirnimesh at gmail.com (Nirnimesh) Date: 2 Nov 2006 04:52:05 -0800 Subject: urllib2: HTTP Version not supported Message-ID: <1162471925.780264.315870@f16g2000cwb.googlegroups.com> I'm using urllib2 module to fetch a URL from a server which understands HTTP/1.1 only (no HTTP/1.0). urllib2.urlopen() results in "urllib2.HTTPError: HTTP Error 505: HTTP Version not supported". How do I force urllib2 to use HTTP v1.1? Regards, Nirnimesh From breakfastea at gmail.com Thu Nov 9 09:37:55 2006 From: breakfastea at gmail.com (Camellia) Date: 9 Nov 2006 06:37:55 -0800 Subject: UnboundLocalError Message-ID: <1163083074.786927.184170@i42g2000cwa.googlegroups.com> hi all why it generates an "UnboundLocalError" when I do the following: ... def main(): number = number() number_user = user_guess() while number_user != number: check_number(number = number, number_user = number_user) number_user = user_guess() UnboundLocalError: local variable 'number' referenced before assignment I found when I changed the number() to num() or whatever the issue solved but doesn't every function has its own namespace? Can anyone please explain it to me? Peace From skip at pobox.com Thu Nov 2 10:43:41 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 2 Nov 2006 09:43:41 -0600 Subject: string formatter for tuple In-Reply-To: <454A126F.6040402@tim.thechases.com> References: <1162481557.791817.41690@b28g2000cwb.googlegroups.com> <454A126F.6040402@tim.thechases.com> Message-ID: <17738.4653.362067.524738@montanaro.dyndns.org> >>>>> "Tim" == Tim Chase writes: >> How can I print a tuple with a single string format? Tim> print "a = %s" % str(a) Tim> or Tim> print "a = %s" % repr(a) Or wrap the tuple in a tuple: print "a = %s" % (a,) Skip From phil_nospam_schmidt at yahoo.com Sun Nov 26 00:23:30 2006 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 25 Nov 2006 21:23:30 -0800 Subject: About alternatives to Matlab References: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> <1163711343.870829.110030@h48g2000cwc.googlegroups.com> <1163720268.611923.3180@e3g2000cwe.googlegroups.com> <1164331082.270046.290720@l39g2000cwd.googlegroups.com> <1164504562.834005.197830@l39g2000cwd.googlegroups.com> Message-ID: <1164518610.895461.252690@45g2000cws.googlegroups.com> sturlamolden wrote: > Using Python just for the sake of using Python is silly. Well, that kind of gets right to my point. Does the "added" effort with Python to interface with data acquisition hardware really result in less productivity? I am very familiar with Matlab, Labview, and Python, and frankly, Python is the most productive and powerful programming language of the three. But it's the hardware compatibility thing that concerns me with Python. It seems the answers are hard to come by on this issue. I sure would be willing to give it a try, except that I'm getting paid to get a job done, not to tinker around with Python and DAQ hardware. But if tinkering around could save my project money on commercial software, and still get it done on schedule, it would be a big win. I just don't have confidence that it would. Phil From p.lavarre at ieee.org Thu Nov 9 19:54:44 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 9 Nov 2006 16:54:44 -0800 Subject: pack a three byte int References: <1163027401.386603.263030@k70g2000cwa.googlegroups.com> <1163092047.577688.140400@m73g2000cwd.googlegroups.com> <1163114202.636000.234900@m73g2000cwd.googlegroups.com> <1163115840.190634.5800@m73g2000cwd.googlegroups.com> Message-ID: <1163120084.037904.250990@h48g2000cwc.googlegroups.com> > Help, what did you mean by the question? How does Python express the idea: i) Produce the six bytes '\x08' '\x01\x23\x45' '\x80' '\0' at run-time when given the tuple (0x08, 0x12345, 0x80, 0). ii) Produce the six bytes '\x12' '\0\0\0' '\x24' '\0' when given the tuple (0x12, 0, 0x24, 0). iii) And so on. So far, everything I write is ugly. Help? > Looks like you ignored ... I guess you're asking me to leave the mystery of my question alone long enough to show more plainly that indeed I am trying to make sense of every word of every answer. I guess I should do that in separate replies, cc'ed back into this same thread. Please stay tuned. Thanks in advance, Pat LaVarre From larsnostdal at gmail.com Thu Nov 2 00:58:43 2006 From: larsnostdal at gmail.com (=?iso-8859-1?q?Lars_Rune_N=F8stdal?=) Date: Thu, 02 Nov 2006 06:58:43 +0100 Subject: logo design References: <1162103065.460796.303660@f16g2000cwb.googlegroups.com> <1162270625.966859.194730@m73g2000cwd.googlegroups.com> <1162377308.044332.212610@i42g2000cwa.googlegroups.com> <1162432978.995731.291980@f16g2000cwb.googlegroups.com> <1162442892.041281.321270@i42g2000cwa.googlegroups.com> Message-ID: On Thu, 02 Nov 2006 06:08:00 +0100, Lars Rune N?stdal wrote: > On Wed, 01 Nov 2006 20:48:12 -0800, Geoffrey Summerhayes wrote: > >> Picture this: Hey, I'm switching to COBOL because its new >> logo looks great on t-shirts and mugs. > > Maybe the extra funding would improve "COBOL" and its libraries faster by > letting a developer work more often on it. (and you'd switch to "COBOL" later down the road because of this) > > I'm not totally serious; but maybe some way of donating money to further > improvement of SBCL/Slime/something-cool-and-universally-needed-here would > be OK or something. > > ..I need a new t-shirt anyways; the Ubuntu t-shirt has gone missing.. :( -- Lars Rune N?stdal http://lars.nostdal.org/ From steve at holdenweb.com Thu Nov 9 08:36:17 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Nov 2006 07:36:17 -0600 Subject: assigning values in __init__ In-Reply-To: References: <454faf57$0$12993$c3e8da3@news.astraweb.com> <4550daa6$0$26446$c3e8da3@news.astraweb.com> <4551fe01$0$7047$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Thu, 09 Nov 2006 12:27:12 +1100, Ben Finney wrote: > >> John Salerno writes: >> >>> Ben Finney wrote: >>>> If you pass a *mapping* of the >>>> "I-might-want-to-add-more-in-the-future" values, then you get both >>>> explicit *and* expandable, without an arbitrary unneeded sequence. >>> Do you mean by using the **kwargs parameter? >> No. > > Well, that'll teach me to put words in your mouth. > > [snip] >> If you have a group of named, semantically-related, unsequenced values, >> pass them into the function as a mapping object (a dict object). > > Still, if you are doing this: > > mapping_object = {"strength": roll_dice(10), > "intelligence":roll_dice(10), > "dexterity":roll_dice(10)} > my_character = Character(mapping_object) > > then there is little benefit to building the dict just for the purposes of > passing it to Character(), never to use it again, not when you can do this: > > my_character = Character(strength: roll_dice(10), > intelligence:roll_dice(10), dexterity:roll_dice(10)) > Except, of course, that you *can't* do that: I think you meant to use equals signs instead of colons? > If you happen to already have collected your character attributes in a > mapping object for some other reason, then well and good, pass it into the > function. Otherwise, well, I believe the correct container for > character attributes is a Character, not a dict. > regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fdjcomp at yahoo.com Wed Nov 1 23:07:32 2006 From: fdjcomp at yahoo.com (frederik aa de jonge) Date: Thu, 02 Nov 2006 04:07:32 +0000 Subject: module for calculations involving radioactive decay? Message-ID: <45496e67$0$10073$a729d347@news.telepac.pt> does anybody know of a package/module which will facilitate/simplify calculations with radioactive samples? as a minimum spec: - user definable list of radionuclides + names + halflives (expressable in time units like sec min etc as appropriate) - choice of units (Bq or Ci, with appropriate modifiers kGM etc - initial activity at given time (sample calibration) - activity calculation at other times, taking into account timezones - operators: add, subtract to simulate adding or removing activity (needs an "history" mechanism, so that activity at time T is always correctly calculated) any help kindly appreciated Frederik From antroy at gmail.com Thu Nov 9 07:02:05 2006 From: antroy at gmail.com (Ant) Date: 9 Nov 2006 04:02:05 -0800 Subject: Exception Handling in TCPServer (was; Problem exiting application in Windows Console.) In-Reply-To: References: <1162987854.490880.46820@h54g2000cwb.googlegroups.com> <1163001245.707034.310900@f16g2000cwb.googlegroups.com> <1163007018.221972.93580@b28g2000cwb.googlegroups.com> Message-ID: <1163073725.471882.225700@h48g2000cwc.googlegroups.com> Steve Holden wrote: ... > First of all, five hour response time is a high expectation, you must be > a Platinum customer :-) I'm in the last week of my current job - start a new one on Monday, and so I haven't got a great deal to do at the moment. Five hours is a lifetime when you're staring at a newsgroup waiting for it to change ;-) > Secondly, while a try/except catching all exceptions *is* unusual it's > justifiable in a server context (though some logging and/or analysis > certainly wouldn't go amiss). True. And I'd expected that the exception ought to be passed to the handle_error method so that something could be done with it there. This morning however I discovered that Guido's been in his time machine since yesterday and provided the very useful sys.exc_info() function for this very purpose! > Thirdly your "ugly hack" *could* be replaced by something cleaner with > more analysis of the trace structure, but given how infrequently this > code is going to run and the low probability that anything else will > trigger the hook I'd be happy with it as it is. But that's just me ... The sys.exc_info() was what I was looking for it turns out, I can get the exception type from that instead of trying to parse the stack trace. However: Gabriel Genellina wrote: ... > Replace serve_forever with your own loop checking an exit flag, and > set the flag in your "quit.html" handler instead of sys.exit(0) This is the approach I decided to go for. I found that RequestHandler objects have a reference to its server that I can use to control the server. Thanks for the input chaps! From tleeuwenburg at gmail.com Tue Nov 28 21:55:38 2006 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 28 Nov 2006 18:55:38 -0800 Subject: HTML Table-of-Content Extraction Script In-Reply-To: References: Message-ID: <1164768938.421866.158160@14g2000cws.googlegroups.com> Fredrik Lundh wrote: > robert wrote: > > > I'm looking for a function which extracts a table of contents > > of HTML file(s) from ... > > and possibly auto-creates the ancors. > > Maybe something already exists? > > that's the kind of stuff you'll write in approximately two minutes using > BeautifulSoup (or if you prefer the ElementTree API, ElementSoup). > > start here: > > http://www.crummy.com/software/BeautifulSoup/ > > splity does that, but it's not Python. Cheers, -T From steve at holdenweb.com Thu Nov 9 16:01:46 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Nov 2006 15:01:46 -0600 Subject: How to choose the right GUI toolkit ? In-Reply-To: <1163103151.772022.300950@k70g2000cwa.googlegroups.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163092380.301382.113470@m7g2000cwm.googlegroups.com> <1163102807.741768.195310@m73g2000cwd.googlegroups.com> <1163103151.772022.300950@k70g2000cwa.googlegroups.com> Message-ID: Dan Lenski wrote: > John Henry wrote: >> I assume you meant that the example programs looks LabView-like GUIs? >> PythonCard itself has nothing in common with LabView. It's more like >> HyperCard. > > That's right, I'm saying the GUIs *produced* by PythonCard look like > those produced by LabView. Believe me, if the PythonCard programming > style had anything to do with LabView, I'd avoid it like the plague =) > > In any case, I think I'm gonna give PythonCard a shot before trying > full-fledged wxPython. It looks ideal for my needs. > You may find that it starts out fine, but becomes less satisfactory as the sophistication of your interfaces increases. Then the problem will be that migration to another platform demands a substantial rewrite of your application (I have done this for a fairly small app). I don't think PythonCard gets much maintenance nowadays. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From nicolasg at gmail.com Wed Nov 8 18:35:31 2006 From: nicolasg at gmail.com (NicolasG) Date: 8 Nov 2006 15:35:31 -0800 Subject: Python to tell what is the IP of my PC . Message-ID: <1163028931.055027.170040@h48g2000cwc.googlegroups.com> How can I use python to get the real IP address of my DSL router (when my PC is part of the local home LAN) ? From istvan.albert at gmail.com Thu Nov 30 11:20:16 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 30 Nov 2006 08:20:16 -0800 Subject: why would anyone use python when java is there? In-Reply-To: <1164874749.914101.32410@16g2000cwy.googlegroups.com> References: <1164762232.220759.57160@h54g2000cwb.googlegroups.com> <1164764454.043697.125730@j72g2000cwa.googlegroups.com> <1164874749.914101.32410@16g2000cwy.googlegroups.com> Message-ID: <1164903616.527678.15410@f1g2000cwa.googlegroups.com> gavino wrote: > I want to learn to program and I can't seem to pick a direction. A Learning how to program and learning a programming language are completely different things. The former far more difficult then the latter. There is nothing better than Python to learn how to program because it is simple and lets you focus on modeling the problem. > experience sees only java people making money.. aggkk!! Nonsense, learning languages is easy, going from Python to Java is easy (but annoying of course) Worry about learning how to program, later you can pick any language you think migh make you rich. i. From fredrik at pythonware.com Sun Nov 26 06:37:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 26 Nov 2006 12:37:38 +0100 Subject: Dynamic function execution In-Reply-To: <8t1n34-qsv.ln1@lairds.us> References: <1164469406.980376.194150@h54g2000cwb.googlegroups.com> <8t1n34-qsv.ln1@lairds.us> Message-ID: Cameron Laird wrote: > ? Or am I missing the point that a better example of what > Mr. Wu really wants is > > def func(seconds = None, minutes = None, hours = None): > print seconds > print minutes > print hours > > dimension = "minutes" > func(**{dimension: 30}) I assumed that the OP was looking for a mechanism that allowed him to use strings for parameter names, not that he wasn't able to replace a literal with a variable once he knew what mechanism to use... From ogbash at gmail.com Thu Nov 30 18:28:24 2006 From: ogbash at gmail.com (Oleg Batrashev) Date: 30 Nov 2006 15:28:24 -0800 Subject: best way to align words? In-Reply-To: <1164925391.696612.64860@80g2000cwy.googlegroups.com> References: <1164925391.696612.64860@80g2000cwy.googlegroups.com> Message-ID: <1164929304.896328.24560@79g2000cws.googlegroups.com> > i would like to write a piece of code to help me to align some sequence > of words and suggest me the ordered common subwords of them Im not sure what you want, but in case you are guy who knows how quicksort and Djikstra algorithms work :) and wants to find out more. There are many algorithms out there, discovered on "Text algorithms" univesity course. The first one does not directly solve your problem - "edit distance" (Levenshtein distance) http://en.wikipedia.org/wiki/Levenshtein_distance I mention it here only because it is simple and shows basic idea of Dynamic Programming http://en.wikipedia.org/wiki/Dynamic_programming If you scroll down you'll see "Longest common subsequence problem" with implementation in Python for 2 sequences. If you dont understand how it works just look into "edit distance" idea and see it is exactly the same algorithm with changed rules. Oleg From steve at holdenweb.com Fri Nov 10 13:25:02 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Nov 2006 12:25:02 -0600 Subject: comparing Unicode and string In-Reply-To: References: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> <1161281095.174018.223790@f16g2000cwb.googlegroups.com> <1161595714.342067.51350@e3g2000cwe.googlegroups.com> <1163120577.369133.279080@h48g2000cwc.googlegroups.com> Message-ID: Neil Cerutti wrote: > On 2006-11-10, luc.saffre at gmail.com wrote: >> Marc 'BlackJack' Rintsch wrote: >>> Why? Python strings are *byte strings* and bytes have values in the range >>> 0..255. Why would you restrict them to ASCII only? >> Because getting an exception when comparing a string with a unicode >> string is irritating. >> >> But I don't insist on my PEP. The example just shows just >> another pitfall with Unicode and why I'll advise to any >> beginner: Never write text constants that contain non-ascii >> chars as simple strings, always make them Unicode strings by >> prepending the "u". > > That doesn't do any good if you aren't writing them in unicode > code points, though. > You tell the interpreter what encoding your source code is in. It then knows precisely how to decode your string literals into Unicode. How do you write things in "Unicode code points"? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From powernews at libero.it Mon Nov 27 08:01:03 2006 From: powernews at libero.it (halex2000) Date: Mon, 27 Nov 2006 13:01:03 GMT Subject: working with files and directories References: <7IAah.58105$uv5.416763@twister1.libero.it> <2YAah.18835$Sw1.13785@newssvr13.news.prodigy.com> Message-ID: "Bryan Olson" ha scritto nel messaggio news:2YAah.18835$Sw1.13785 at newssvr13.news.prodigy.com... > halex2000 wrote: >> Hi all, I'm new with Python, and I thought to use it to automatically >> rename some files in a directory, but I don't know where should I search >> the functions: to get all the files of a directory, to rename the files >> and so on. > > Python programmers are constantly looking at: > > http://docs.python.org/lib/lib.html > > In this case, see 14.1.4, 11.1, and 11.10. > > Happy hacking. > > -- > --Bryan > Thank you very much :-) From martin at v.loewis.de Sun Nov 19 18:07:26 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 20 Nov 2006 00:07:26 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: <3e540$4560b958$59ad1aca$32456@news.flashnewsgroups.com> References: <18c54$455d019b$59ad1aca$24364@news.flashnewsgroups.com> <455d507d$0$18480$9b622d9e@news.freenet.de> <3188c$455d923f$59ad1aca$4742@news.flashnewsgroups.com> <455E5D15.7030207@v.loewis.de> <3e540$4560b958$59ad1aca$32456@news.flashnewsgroups.com> Message-ID: <4560E3AE.5030307@v.loewis.de> gabor schrieb: > 1. simply fix the documentation, and state that if the file-name cannot > be decoded into unicode, then it's returned as byte-string. For 2.5, this should be done. Contributions are welcome. [...then] > [os.path.join(path,n) for n in os.listdir(path)] > > will not work. > > 2. add support for some unicode-decoding flags, like i wrote before I may have missed something, but did you present a solution that would make the case above work? > 3. some solution. One approach I had been considering is to always make the decoding succeed, by using the private-use-area of Unicode to represent bytes that don't decode correctly. Regards, Martin From jseigh_01 at xemaps.com Tue Nov 7 09:06:59 2006 From: jseigh_01 at xemaps.com (Joe Seigh) Date: Tue, 07 Nov 2006 09:06:59 -0500 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <7xk62ct5pf.fsf@ruckus.brouhaha.com> References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <7xk62ct5pf.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > robert writes: > >>>I don't want to discourage you but what about reference >>>counting/memory >>>management for shared objects? Doesn't seem fun for me. >> >>in combination with some simple locking (anyway necessary) I don't >>see a problem in ref-counting. >>If at least any interpreter branch has a pointer to the (root) >>object in question the ref-count is >0. ---- >>Question Besides: do concurrent INC/DEC machine OP-commands execute >>atomically on Multi-Cores as they do in Single-Core threads? > > > Generally speaking, no, the inc/dec instructions are not atomic. You > can do an atomic increment on the x86 using LOCK XCHG (or maybe LOCK > INC is possible). The thing is that the locking protocol that > guarantees atomicity is very expensive, like 100x as expensive as an > unlocked instruction on a big multiprocessor. So yes, of course you > could accomplish reference counting through locks around the ref > counts, but performance suffers terribly. The solution is to get rid > of the ref counts and manage the entire heap using garbage collection. Atomic increment and decrement instructions are not by themselves sufficient to make reference counting safe. It's what Boost::shared_ptr uses to make itself internally thread-safe but it's not safe to copy a shared_ptr without "owning" it. Not like Java where you can safely copy a reference (Java pointer) no matter what. Basically there's a race condition where an object containing the refcount can be deleted between the time you load a pointer to the object and the time you increment what used to be a refcount and is possibly something else but definitely undefined. I have an experimental refcounting implementation at http://atomic-ptr-plus.sourceforge.net/ > > For stuff like dictionary access, there are protocols (again based on > LOCK XCHG) that don't require locking for lookups. Only updates > require locking. Simon Peyton-Jones has a good paper about how it's > done in Concurrent Haskell: > > http://research.microsoft.com/~simonpj/papers/stm/stm.pdf > > This is really cool stuff and has found its way into Perl 6. I'd like > to see Python get something like it. That seems to be about STM (Software Transactional Memory). What you're describing seems to be read lock-free using what I call PDR (PCOW (Partial Copy On Write) Deferred Reclaimation). Examples of PDR are RCU (used in Linux kernel), Maged Michael's SMR hazard pointers, and thread-safe GC (used in Java's concurrent collections java.util.concurrent). You can also use PDR to manage safe refcounting ,e.g. RCU based refcounting, rcuref, in the Linux kernel. -- Joe Seigh When you get lemons, you make lemonade. When you get hardware, you make software. From p.lavarre at ieee.org Thu Nov 9 20:09:04 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 9 Nov 2006 17:09:04 -0800 Subject: pack a three byte int References: <1163027401.386603.263030@k70g2000cwa.googlegroups.com> Message-ID: <1163120944.551169.293230@h48g2000cwc.googlegroups.com> Speaking as the OP, perhaps I should mention: > > [-3:] to [1:] is a minor cosmetic improvement To my eye, that's Not an improvement. '\x08' '\x01\x23\x45' '\x80' '\0' is the correct pack of (0x08, 0x12345, 0x80, 0) because '\x01\x23\x45' are the significant low three bytes of a big-endian x12345, thus [-3:]. The [1:] fact that we can keep the 3 significant bytes by tossing exactly 1 byte away after rounding the bit length of that digital number up to the nearest power of two which happens to be 4 = 3 + 1 is merely incidental - not of central significance. From 12.nitro at gmail.com Thu Nov 9 05:38:33 2006 From: 12.nitro at gmail.com ([12]Nitro) Date: 9 Nov 2006 02:38:33 -0800 Subject: cx_Oracle and NCLOBs Message-ID: <1163068713.669375.308900@b28g2000cwb.googlegroups.com> Greetings, I'm currently working in a Python project to create a multi-platform database replication tool, and cx_Oracle was the chosen provider to handle the Oracle connections. So far the results have been very interesting, but I've been experiencing some problems when inserting CLOB objects through executemany (meaning, using a pre-prepared statement and a dynamic list of parameters). Namely, somehow the provider seems to be converting the data to LONG rather than to CLOB, even though the statement explicitly calls out the TO_NCLOB function; therefore, we get ORA-01461 errors. Now, this may possibly not be an error, but instead a misusage (not many examples available, anyways). Any help/suggestion you can provide? Best regards, Nitro From fredrik at pythonware.com Thu Nov 16 05:41:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 11:41:24 +0100 Subject: ANN: pyfaq 1.0b1 is now available In-Reply-To: <1163630914.818184.210590@e3g2000cwe.googlegroups.com> References: <1163630914.818184.210590@e3g2000cwe.googlegroups.com> Message-ID: John Machin wrote: > P.S. Great job on the wiki, and yes a search facility a tad smarter > than browser Ctrl-F would be a very good idea! the "effbot.org" version of the PyFAQ is basically just an editing and staging area; when everyone involved gets enough spare cycles, the plan is (or at least was) that it's going to be republished here: http://www.python.org/doc/faq/ and thus be covered by python.org's search engine, like everything else on that site. (but maybe one could use google's new community search, or whatever it's called, to set up a local search engine for the pyfaq/pyref/pytut zones. hmm. that's one more thing on my todo list...) From tdelaney at avaya.com Sun Nov 19 19:39:05 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 20 Nov 2006 11:39:05 +1100 Subject: syntax error in sum(). Please explicate. Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1EBB7@au3010avexu1.global.avaya.com> John Machin wrote: > Michael Press wrote: >> I have not written python codes nor run any. I saw this >> code posted and decided to try it. It fails. I read the >> tutorial and the entry for the built in function sum, >> but still do not see the problem. The code was cut and >> paste. > > I doubt it -- "none" should be "None" Not necessarily. He said he cut-and-pasted - I interpreted that to be from *his* editor. But since he was getting a SyntaxError, he would not have hit the NameError yet ... All-in-all, this actually felt like a post from someone who *had* read: http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney From hg at nospam.com Wed Nov 22 14:21:57 2006 From: hg at nospam.com (hg) Date: Wed, 22 Nov 2006 13:21:57 -0600 Subject: utf - string translation In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > hg wrote: > >> How would you handle the string.maketrans then ? > > maketrans works on bytes, not characters. what makes you think that you > can use maketrans if you haven't gotten the slightest idea what's in the > string? > > if you want to get rid of accents in a Unicode string, you can do the > approaches described here > > http://www.peterbe.com/plog/unicode-to-ascii > > or here > > http://effbot.org/zone/unicode-convert.htm > > which both works on any Unicode string. > > > Thanks From cliff at develix.com Tue Nov 7 17:16:04 2006 From: cliff at develix.com (Cliff Wells) Date: Tue, 07 Nov 2006 14:16:04 -0800 Subject: Pyro stability In-Reply-To: <1162866001.849724.245510@b28g2000cwb.googlegroups.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <454dd84b$0$328$e4fe514c@news.xs4all.nl> <1162783631.291535.221530@f16g2000cwb.googlegroups.com> <454fdbc5$0$335$e4fe514c@news.xs4all.nl> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> Message-ID: <1162937764.3199.25.camel@localhost.localdomain> On Mon, 2006-11-06 at 18:20 -0800, Beliavsky wrote: > Carl J. Van Arsdall wrote: > > > > > Pyro is fucking amazing and has been a great help to a couple of our projects. > > You should watch your language in a forum with thousands of readers. The LA Times had a story that claimed that 64% of U.S. citizens use the word "fuck" and that 74% of us have heard it in public (I'll assume the remainder are your fellow AOL users). I expect extrapolating these results worldwide wouldn't be far off the mark (the Brits were quite successful at spreading this versatile word). I think the gap between what people actually find offensive and what people are afraid others will find offensive is pretty wide indeed. Regards, Cliff From bignose+hates-spam at benfinney.id.au Fri Nov 10 03:29:36 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 10 Nov 2006 19:29:36 +1100 Subject: how is python not the same as java? References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> <87k624j622.fsf@benfinney.id.au> Message-ID: <878xijk8lr.fsf@benfinney.id.au> Steve Holden writes: > Ben Finney wrote: > > Steve Holden writes: > >> Java is horrible, Oython is not. > > Is that the predecessor to Python, the one that could only be > > expressed in vowel noises? > > > You're taking the oiss, right? Oardon. I never meant to ooke fun at your tyoing imoediment. -- \ "For mad scientists who keeo brains in jars, here's a tio: why | `\ not add a slice of lemon to each jar, for freshness?" -- Jack | _o__) Handey | Ben Finney From ajikoe at gmail.com Wed Nov 15 01:07:57 2006 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 14 Nov 2006 22:07:57 -0800 Subject: reading csv problem Message-ID: <1163570877.075189.174670@m73g2000cwd.googlegroups.com> Hello, I use csv to take information from file. import csv reader = csv.reader(open('t.csv')) for row in reader: print row # it is perfectly OK --------------------------------------------------------------------- But If I use this code I have problem import csv reader = csv.reader(open('t.csv')) for row in reader: print row # it is perfectly OK for row in reader: print row # it is not printed on the monitor??? Why does only the first print row work here? TIA, ajikoe From tim at tdw.net Fri Nov 10 11:25:26 2006 From: tim at tdw.net (Tim Williams) Date: Fri, 10 Nov 2006 16:25:26 +0000 Subject: Getting externally-facing IP address? In-Reply-To: References: Message-ID: <9afea2ac0611100825o1115c188uc89ee1fbe0434717@mail.gmail.com> On 10/11/06, Michael B. Trausch wrote: > > > > Every programming example that I have seen thus far shows simple server > code and how to bind to a socket--however, every example binds to the > localhost address. What I am wondering is this: Is there a clean way to > get the networked IP address of the machine the code is running on? For > example, my laptop's IP address is 192.168.0.101, and I want to bind a > server to that address. Is there a clean way of doing so that will work, > for example, when I move the code to my server (which obviously doesn't have > the same IP address)? > > Try using 0.0.0.0 as the IP address, or possibly giving IP address at all. HTH :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE.THIS.cybersource.com.au Thu Nov 2 08:28:05 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 03 Nov 2006 00:28:05 +1100 Subject: __div__ not recognized automatically References: Message-ID: On Thu, 02 Nov 2006 12:59:32 +0100, Anton81 wrote: > When I execute the program it > complains that it can't find an operator "/" for "instance" and "integer". How about if you post the actual traceback you get, rather than paraphrasing? That way, we don't have to guess. -- Steven. From inq1ltd at verizon.net Fri Nov 17 14:27:09 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Fri, 17 Nov 2006 14:27:09 -0500 Subject: Press button to load data In-Reply-To: References: <1163650825.563379.38550@b28g2000cwb.googlegroups.com> Message-ID: <200611171427.09452.inq1ltd@verizon.net> On Friday 17 November 2006 02:58, you wrote: > On Fri, 17 Nov 2006 00:25:39 -0500, > jim-on-linux > > declaimed the following in comp.lang.python: > > Without being able to run the code my > > question is where is the id in the lambda > > defined? > > Please take into account that I've not > actually used lambdas, so might have some > mistakes in the syntax... > > > > for bill in shelvename: > > > global funcs > > > bill1 = Button(None, text= > > > shelvename[bill].name, > > > font=('bold',10),command=(lambda x = id: > > > fetchRecord(x))) > > "id" would be something that "identifies" the > button... In this case, maybe you can use > "bill": > Think about relating a Tkinter variable to each button then the button is related to a unique variable. ( Tkinter StingVar or IntVar or some others.) Then you will have to keep the variables in a list or dictionary for recalling. jim-on-linux http://www.inqvista.com > ... command=(lambda x = bill: fetchRecord(x)) > ... > > As I understand the lambda syntax, what this > does is create a "function" (which is the > command that gets run when the button is > pushed), and this function will call > fetchRecord passing it the value that "x" had > at the time of definition (hence the x=...) > -- > 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 ironpythonster at gmail.com Mon Nov 6 04:11:58 2006 From: ironpythonster at gmail.com (ironpythonster at gmail.com) Date: 6 Nov 2006 01:11:58 -0800 Subject: Is there any python lib for calling CVS api? Message-ID: <1162804318.492725.245410@f16g2000cwb.googlegroups.com> Hi everyone, this should be a quick question. I'm writing some scripts to take some file and move them into a CVS repository, but it's pretty slow, because it uses system calls to execute the CVS commands. Has anyone ever made a python to CVS interface library that I could use? Some one sugestion me use the cvsgui lib,but it look like that the lib could not use fro Python2.4.I've been trying to google around for something, but predictably I get a zillion sourceforge repository hits, and it isn't really helping. So anyway, if anyone knows of a useful module, I'd love to hear about it. Thanks! From xi at gamma.dn.ua Sun Nov 19 08:58:19 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Sun, 19 Nov 2006 15:58:19 +0200 Subject: A python IDE for teaching that supports cyrillic i/o In-Reply-To: References: Message-ID: <20061119135818.GA12399@58sirius016.dc.ukrtel.net> On Sun, Nov 19, 2006 at 12:33:39PM +0100, Alan Franzoni wrote: > Kirill Simonov si ? divertito a scrivere: > > > Unfortunately, most IDEs I tried failed miserably in this respect. My > > test was simple: I've run the code > > name = raw_input("What's your name? ") # written in Russian > > print "Hello, %s!" % name # in Russian as well > > both from the shell and as a standalone script. This either caused a > > UnicodeError or just printed invalid characters. > > I highly dislike asking stupid questions, and this might be stupid > indeed... but did you write > > # -*- coding: iso-8859-5 -*- > > or > > # -*- coding: koi8_r -*- > > (they both seem suited to the Russian language, but I don't know the > difference) They are different encodings for the same character set. The latter is mostly used under Unices, and the former is not used anywhere as far as I know. There are two more cyrillic encodings: cp866 and cp1251 - for DOS and Windows correspondingly. > as the first line in your .py file? No, I would prefer the editor to save the .py files with non-ASCII characters in UTF-8 encoding adding the BOM at the beginning of the file. This will allow the interpreted to detect the file encoding correctly and would save a teacher from explaining what an encoding is and why it is needed. > Personally, I use Eclipse+Pydev (a bit steep to learn at the beginning, and > quite memory and cpu hogging since it's a java-based ide; don't use it on > old/slow computers with less than 512MB RAM, and don't use version < 3.2 > either) and it uses that very line to recognize the actual character set > employed. You may check with other encodings as well. Unfortunately, the Eclipse CPU/memory requirements are extremely high for a high school, so I haven't even tried it. -- xi From python.list at tim.thechases.com Tue Nov 21 11:26:26 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 21 Nov 2006 10:26:26 -0600 Subject: Software Compatable with other versions? In-Reply-To: References: <1164113768.450227.161750@m73g2000cwd.googlegroups.com> Message-ID: <456328B2.3080303@tim.thechases.com> >>> I have been told that the .pyc are not compatable. Is it >>> possible, to convert a 2.4.x .pyc to a 2.5 .pyc? > > The magic code. > > Just rm -rf *.pyc from your own scripts directories, they will > be rebuilt. Just take care in the event that you have files that were distributed in bytecode format (.pyc) rather than source form...if you don't have any such .pyc files, then Laurent's solution is fast and easy. If you do, you may have to protect them before trying such a stunt. -tkc From mike at hobbshouse.org Thu Nov 9 11:16:53 2006 From: mike at hobbshouse.org (Michael Hobbs) Date: Thu, 09 Nov 2006 10:16:53 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> Message-ID: <45535475.9090207@hobbshouse.org> Can anyone find a flaw with this change in syntax? Instead of dividing a compound statement with a colon, why not divide it on a newline? For example, the colon could be dropped from this statement: if self.hungry: self.eat() to if self.hungry self.eat() Python is already sensitive to whitespace and the newline anyway, so why not put it to good use? For example, Python rejects this statement because of the newline present: if self.hungry or self.depressed: self.eat() You need to use the backslash to continue the expression on the next line: if self.hungry or \ self.depressed: self.eat() The colon that divides the statement therefore seems redundant. The colon could continue to be used for single-line statements: if self.hungry: self.eat() I think the colon could be omitted from every type of compound statement: 'if', 'for', 'def', 'class', whatever. Am I missing anything? Thanks, - Mike From fredrik at pythonware.com Sat Nov 11 02:50:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Nov 2006 08:50:05 +0100 Subject: Py3K idea: why not drop the colon? In-Reply-To: <022001c7055a$b24c7860$03000080@hendrik> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> <4rjlkqFrlskqU1@mid.individual.net> <4rk5giFrerjfU1@mid.individual.net> <022001c7055a$b24c7860$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: >> blue is red or green or yellow > > *grin* - this can be construed as a weakness in Python - it's boolean logic, and it's incompatible with human use of the same terms in all contexts, not just Python. From fredrik at pythonware.com Tue Nov 28 03:20:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 28 Nov 2006 09:20:15 +0100 Subject: Error when installing the Python Imaging Library In-Reply-To: <1164700897.128779.180580@j44g2000cwa.googlegroups.com> References: <1164700897.128779.180580@j44g2000cwa.googlegroups.com> Message-ID: Tim Adler wrote: > I'm quite new to Python. I'm working on a webproject with Django and > need to install the Python Imaging Library. It worked fine under Mac OS > but when I try it on my Linux server. It gives me this error: > > PasteBin Link: http://phpfi.com/179314 > > I don't really know what is wrong. Can somebody point me directions. I > really need the PIL to work. the important line is _imagingtk.c:20:16: tk.h: No such file or directory which indicates that you don't have complete Tcl/Tk development libraries on your machine (but you obviously have enough pieces of them for PIL to think that you have them). look for tcl-devel and tk-devel or similar packages in your Linux provider's package repository. From mail at microcorp.co.za Thu Nov 16 00:40:12 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 16 Nov 2006 07:40:12 +0200 Subject: Decimal() instead of float? References: <1163294604.4675.4.camel@pepper> <1163511997.4675.88.camel@pepper><4559F828.7070704@holdenweb.com> Message-ID: <017c01c7094b$8539bfa0$03000080@hendrik> "Fredrik Lundh" wrote: > ...... and seriously, under- > standing the various aspects of floats and decimals is utterly trivial > compared to all the nearly-magical things you need to understand to be > able to do geographical calculations at a sub-millimeter scale. heck, > even sub-kilometer stuff is pretty hard to get right ;-) This is true - have you looked at that thing they call a geode? - horrible... I can never understand why people grab for floats at the first opportunity. To my simple mind, it seems better to work with a sub unit, and to stick to integer arithmetic - if, as Steve said, there is a speed penalty for changing from floats to decimal. then you can make even a cripple processor look good by sticking to integers - unless you run out of precision... - Hendrik From fredrik at pythonware.com Tue Nov 14 06:35:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Nov 2006 12:35:15 +0100 Subject: PyFAQ: anyone seen aahz' thread tutorial ? In-Reply-To: <1163503688.391377.191690@e3g2000cwe.googlegroups.com> References: <1163503688.391377.191690@e3g2000cwe.googlegroups.com> Message-ID: Paul Boddie wrote: >> they have disappeared from the starship? any ideas where to look for them ? > > The Internet Archive (the rewind button of the Internet): > > http://web.archive.org/web/20050729075144/http://starship.python.net/crew/aahz/OSCON2001/ but of course. I didn't even bother to look there, because I was sure they didn't cache PDF files. oh well, you learn something every day ;-) thanks /F From larry.bates at websafe.com Mon Nov 6 13:14:29 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 06 Nov 2006 12:14:29 -0600 Subject: how do I pass values between classes? In-Reply-To: <1162796443.570347.91760@e3g2000cwe.googlegroups.com> References: <1162592180.494470.257040@h54g2000cwb.googlegroups.com> <454C9ECF.5020806@websafe.com> <1162796443.570347.91760@e3g2000cwe.googlegroups.com> Message-ID: kath wrote: > hi, Larry Bates .... thanks for the reply... > >> You might consider doing it the same way wx passes things around. >> When you instantiate the subclass pass the parent class' instance >> as first argument to __init__ method. > > Yes thats absolutely right.. > >> That way the subclass can >> easily pass values back to the parent by using that pointer. > > Could you please explain me this.. more clearly. I think it is much > close to the solution. > > > Thank you. > regards, sudhir > Just something like: class foo: self.__init__(self, parent): self.parent=parent class bar: self.__init__(self, parent): self.parent=parent self.foo=foo(self) class myclass: self.__init__(self, parent): self.parent=parent self.bar=bar(self) Now in foo I can reference things from myclass easily self.parent.parent. Or setattr(self.parent.parent, value). Hope this helps. -Larry From fredrik at pythonware.com Thu Nov 2 05:21:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 02 Nov 2006 11:21:31 +0100 Subject: other ways to check for ? In-Reply-To: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> Message-ID: elderic wrote: > are there other ways than the ones below to check for > in a python script? callable(f) From sjmachin at lexicon.net Wed Nov 29 18:08:05 2006 From: sjmachin at lexicon.net (John Machin) Date: 29 Nov 2006 15:08:05 -0800 Subject: utf - string translation In-Reply-To: References: <1164224962.711265.198090@h48g2000cwc.googlegroups.com> <1164226304.119425.206380@h54g2000cwb.googlegroups.com> <1164232741.215312.322990@k70g2000cwa.googlegroups.com> <1164529973.299095.155940@n67g2000cwd.googlegroups.com> <1164829990.146305.92750@l39g2000cwd.googlegroups.com> <1164837136.303079.312060@j44g2000cwa.googlegroups.com> Message-ID: <1164841685.745779.268920@l12g2000cwl.googlegroups.com> Fredrik Lundh wrote: > John Machin wrote: > > > Another point: there are many non-latin1 characters that could be > > mapped to ASCII. For example: > > u"\u0141ukasziewicz".translate(unaccented_map()) > > doesn't work unless an entry is added to the no-decomposition table: > > 0x0141: u"L", # LATIN CAPITAL LETTER L WITH STROKE > > > > It looks like generating extra entries like that could be done, with > > the aid of unicodedata.name(): > > > > LATIN CAPITAL LETTER X WITH blahblah -> "X" > > LATIN SMALL LETTER X WITH blahblah -> "X".lower() > > > > This would require a fair bit of care -- obviously there are special > > cases like LATIN CAPITAL LETTER O WITH STROKE. Eyeballing by regional > > experts is probably required. > > see the comments over at > > http://effbot.org/zone/unicode-convert.htm Don't rush me, I was getting to that next :-) > > for an extended table, eyeballed by a regional expert (and since he > makes the same point about OE vs Oe as you do, I'll probably have to > change the code ;-) > Slightly extended. My point is that there is a large number of LATIN (CAPITAL|SMALL) LETTER X WITH twiddly-bits that don't have a decomposition; the table entries could be generated automatically As well as regional experts, Google can be handy: googling for Thord, Thordh, Thordsson and Thordhsson and noting the number of hits for each tends to indicate that you and I are right about the treatment of "eth"; Marcin's "dh" might better indicate how it's pronounced, but "d" is AFAICT the standard transcription. Cheers, John From http Fri Nov 3 16:59:39 2006 From: http (Paul Rubin) Date: 03 Nov 2006 13:59:39 -0800 Subject: Sorted and reversed on huge dict ? References: <1162580533.981364.211860@h54g2000cwb.googlegroups.com> <7xvelwib1b.fsf@ruckus.brouhaha.com> <1162590153.024233.311670@b28g2000cwb.googlegroups.com> Message-ID: <7xirhwi438.fsf@ruckus.brouhaha.com> vd12005 at yahoo.fr writes: > but maybe if keys of dicts are not duplicated in memory it can be done > (as all dicts will have the same keys, with different (count) values)? There will still be a pointer for each key, the strings themselves won't be duplicated. > memory is 4Gb of ram, That sounds like enough ram to hold all your stuff easily. > is there a good way to know how much ram is used > directly from python (or should i rely on 'top' and other unix > command? I think try resource.getrusage() > by now around 220mb is used for around 200.000 words handled in 15 > dicts) That sounds very manageable given a 4gb machine. Otherwise, since it sounds like you're trying to scan some big text corpus and figure out word frequencies, you could do it the old fashioned way. Write the words one per line into a big file, then sort the file with the Unix sort utility (which is an external sort), then read the sorted file (or pipe it through "uniq -c") to figure out the counts. From mm2ps at yahoo.co.uk Sun Nov 5 14:19:40 2006 From: mm2ps at yahoo.co.uk (dug) Date: 5 Nov 2006 11:19:40 -0800 Subject: Programming Language that is Spreadsheet/Table Based In-Reply-To: <1162588208.533235.266100@k70g2000cwa.googlegroups.com> References: <1162588208.533235.266100@k70g2000cwa.googlegroups.com> Message-ID: <1162754380.463019.295120@i42g2000cwa.googlegroups.com> I think that Gnumeric lets you do some python stuff. Douglas Omar wrote: > I'm looking for a programming language or module that sorta looks and > feels like MS Excel (I love and think in tables), yet has the power and > open-endedness of python or javascript. I'm still pretty new to > python. > > any ideas? i've been having some fun with VBA in excel, but I want > something I can save as en exe and call my own creation, y'know? From deets at nospam.web.de Sun Nov 26 10:07:43 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 26 Nov 2006 16:07:43 +0100 Subject: Installation problem In-Reply-To: References: Message-ID: <4stotvF10vmqhU1@mid.uni-berlin.de> Tommy Grav schrieb: > Trying to update my ActivePython installation I mistakenly downloaded > the Intel Mac version (rather than the PPC version) and tried to install > it. > The version did install but did not run of course. However, now trying > to install the PPC version of Activepython or even the 2.5 version of > macpython fails (actually macpython installs, but the installation program > tells me there is an error at the end). Anyone know how to completely > remove all previous python installations and all config files so that I can > install it from scratch? Is there also a log of the dmg-installation so > that > I can see what fails with the installation? The custom installed pythons should live under /Library/Frameworks/Python.framework You should be able to move them somewhere else and try again. However, I wouldn't touch /System/Library/Frameworks/Python as that is the OSX shipped one, don't tinker with it. There actually is a program to see what gets installed by a package, where to, and you can even suppress certain parts. But unfortunately, I don't have it installed and don't remember its name. Diez From rtw at freenet.co.uk Thu Nov 9 15:32:42 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Thu, 09 Nov 2006 14:32:42 -0600 Subject: UnboundLocalError References: <1163083074.786927.184170@i42g2000cwa.googlegroups.com> Message-ID: Terry Reedy wrote in news:mailman.1994.1163100168.11739.python-list at python.org in comp.lang.python: >> def main(): >> number = number() > > Within a function, a given name can be either global or local, but not > both. > Here you are expecting the compiler to interpret the first occurance > of 'number' as local and the second as global. Humans can often > resolve such ambiguities correctly, but not necessarily always. So > this is too much to ask of a program and hence it is not allowed. > ".. asked too much of the programme", sounds like a BOFH excuse to me ;-). Seriously I'd bet (if I were a gambling man) that this is by design, not either of "too much work for the interpreter" or "nobody's submitted a patch". IOW: Why should the intepreter do more work just so the user can find new and interesting ways to shoot them selves in the foot. Rob. -- http://www.victim-prime.dsl.pipex.com/ From ardsrk at gmail.com Sat Nov 4 05:17:59 2006 From: ardsrk at gmail.com (ArdPy) Date: 4 Nov 2006 02:17:59 -0800 Subject: small python cgi webserver In-Reply-To: References: Message-ID: <1162635479.491109.15640@h54g2000cwb.googlegroups.com> Fabian Braennstroem wrote: > Hi, > > I am looking for a small python script, which starts a small > web server with python cgi support on a linux machine. > > I tried: > > > #!/usr/bin/env python > import sys > from CGIHTTPServer import CGIHTTPRequestHandler > import BaseHTTPServer > > class MyRequestHandler(CGIHTTPRequestHandler): > # In diesem Verzeichnis sollten die CGI-Programme stehen: > cgi_directories=["/home/fab/Desktop/cgi-bin"] > > > def run(): > # 8000=Port-Nummer > # --> http://localhost:8000/ > # Fuer http://localhost/ > # Port-Nummer auf 80 setzen > httpd=BaseHTTPServer.HTTPServer(('', 8000), MyRequestHandler) > httpd.serve_forever() > > if __name__=="__main__": > print "Starting Server" > run() > > but when I want to test a small python cgi test file: > > > #!/usr/bin/python > # -*- coding: UTF-8 -*- > > # Debugging f?r CGI-Skripte 'einschalten' > import cgitb; cgitb.enable() > > print "Content-Type: text/html;charset=utf-8\n" > print "Hello World!" > > I just get the text and not the html output. The file's mode > is 755. > > Is there anything wrong with the webserver script or do I do > something completely wrong? Maybe, you have a different > webserver script? > > Greetings! > Fabian Probably the server is not executing your CGI script. If it is the Apache web server that you are using then just ensure the following settings in your /etc/httpd/conf/httpd.conf file is exactly like following: AllowOverride None Options ExecCGI Order allow,deny Allow from all From theller at ctypes.org Sat Nov 4 12:13:22 2006 From: theller at ctypes.org (Thomas Heller) Date: Sat, 04 Nov 2006 18:13:22 +0100 Subject: py2exe questions In-Reply-To: References: <454BB574.9030607@websafe.com> <1162646535.744282.95290@m7g2000cwm.googlegroups.com> Message-ID: <454CCA32.7060406@ctypes.org> Marc 'BlackJack' Rintsch schrieb: > In <1162646535.744282.95290 at m7g2000cwm.googlegroups.com>, Jerry wrote: > >> Despite what everyone is saying though, I believe that any and all >> solutions will require that the byte-code be extracted to some >> directory before being run. > > It's not Python bytecode. The problem is native libraries which are hard > to run from memory without a real file backing it on some platforms. A > pure Python program/package should be possible without temporary files. py2exe even achives this on Windows. See http://www.py2exe.org/old/ , and look at the section named "The bundle option". py2exe is able to load Python extensions (.pyd and .dll) from the zip-archive *without* extracting them to the file system at all. It doesn't work for the C runtime library msvcr71.dll though. Thomas From gagsl-py at yahoo.com.ar Tue Nov 7 15:43:13 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 07 Nov 2006 17:43:13 -0300 Subject: C wrapper In-Reply-To: <1162931220.448328.108160@e3g2000cwe.googlegroups.com> References: <1162928252.643092.23350@h48g2000cwc.googlegroups.com> <1162930226.658619.79830@m73g2000cwd.googlegroups.com> <1162931220.448328.108160@e3g2000cwe.googlegroups.com> Message-ID: <7.0.1.0.0.20061107173909.05568188@yahoo.com.ar> At Tuesday 7/11/2006 17:27, Sheldon wrote: >Here is the file/module name: _msgpps_functions.c >Here is the initfunction: > >PyMODINIT_FUNC init_msgpps_functions(void) { > PyObject* m; > m=Py_InitModule("_msgpps_functions",_msgpps_functionsMethods); > ErrorObject = PyString_FromString("_msgpps_functions.error"); > if(ErrorObject == NULL || \ > PyDict_SetItemString(PyModule_GetDict(m),"error",ErrorObject)!=0) >{ > Py_FatalError("Can't define _msgpps_functions.error"); > import_array(); > } /* access to Numeric PyArray functions */ >} > > >I have not main() function in the file. Instead the main function is >called the same name: > >static PyObject* _msgpps_functions(PyObject* self, PyObject* args) > >Now I am new at this and I have been reading anything I can find. The >only thing that is out of place is the part which I didn't include: > > /* Initialize the Python interpreter. Required. */ > Py_Initialize(); > > /* Add a static module */ > initspam(); >because I still don't understand this part. Are you *extending* Python with a new module written in C (you should be using the first part), or *embedding* python inside your application, mainly written in C (you would use something like the last code). -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From gagsl-py at yahoo.com.ar Thu Nov 9 18:39:08 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 09 Nov 2006 20:39:08 -0300 Subject: urlretrieve get file name In-Reply-To: <1163110313.580268.19660@h48g2000cwc.googlegroups.com> References: <1163110313.580268.19660@h48g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20061109202123.03d18800@yahoo.com.ar> At Thursday 9/11/2006 19:11, Sven wrote: >I'm wrestling with the urlretrieve function in the urllib module. I >want to download a file from a web server and save it locally with the >same name. The problem is the URL - it's on the form >http://www.page.com/?download=12345. It doesn't reveal the file name. >Some hints to point me in the right direction are greatly appreciated. The file name *may* come in the Content-Disposition header (ex: Content-Disposition: attachment; filename="budget.xls") Use urlopen to obtain a file-like object; its info() method gives you those headers. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From mauriceling at acm.org Thu Nov 16 16:28:57 2006 From: mauriceling at acm.org (Maurice LING) Date: Thu, 16 Nov 2006 21:28:57 GMT Subject: Will GPL Java eat into Python marketshare? In-Reply-To: <1163711259.597170.116020@e3g2000cwe.googlegroups.com> References: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> <455b978c$1@news.unimelb.edu.au> <_jT6h.7906$ig4.2956@newsread2.news.pas.earthlink.net> <455cc9ae$1@news.unimelb.edu.au> <1163711259.597170.116020@e3g2000cwe.googlegroups.com> Message-ID: <455cd815$1@news.unimelb.edu.au> Stephen Eilert wrote: > Maurice LING escreveu: > > >>>I once wrote a partial JVM in Modula-3 (strictly a researchware >>>effort), so I can imagine it being done technically. But why? >>> >>>The big problem with Java-and-Python is not the VMs underneath. It is >>>the fact that Java has layers upon layers upon layers of idiosyncratic >>>libraries and idioms. When you write bindings to that world (even if >>>the bindings are generated automagically), you have to *think* in >>>those same layers. The Python-oriented developer suddenly has to use >>>a dozen imports in order to do things already done better in >>>Pythonesque libraries. >>> >> >>The main use I can see is to be able to incorporate Java applications >>into Python. For example, I am using Cytoscape (www.cytoscape.org) which >>is in Java. I do hope that I can control Cytoscape from Python and >>manipulate its objects from Python. >> >>Say given cytoscape.jar, I'll like to be able to do this: >> >> >>> from cytoscape javaimport cytoscape >> >>> c = cytoscape() >> >>And the tighest way I see that this can be done is for Python VM to >>execute Java bytecodes like Python bytecodes. That is, Python VM >>executes Java bytecodes directly and not through object mapping which I >>think is that JPyPe is doing. >> >>I must say that this is part of even a fluffier dream that one day, I >>can take any applications and play around with it in Python. Currently, >>my collaborators wrote in Perl and Java, so it is not easy for me to use >>their work in my work. >> >>ML > > > What is wrong with the other way around and Jython? > Nothing wrong with the other way round - JVM executing *Python bytecodes*. Cytoscape has a plugin with enables one to bring up Jython interpreter but it is way too slow - make sure you start to load it up before lunch if you want to execute a few lines of codes after lunch. ML From attn.steven.kuo at gmail.com Thu Nov 9 15:27:10 2006 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 9 Nov 2006 12:27:10 -0800 Subject: Lists of lists and tuples, and finding things within them References: <1163079978.5053.32.camel@pepper> Message-ID: <1163104030.342251.108060@f16g2000cwb.googlegroups.com> Daniel Nogradi wrote: > > I have a program that keeps some of its data in a list of tuples. > > Sometimes, I want to be able to find that data out of the list. Here is > > the list in question: > > > > [('password01', 'unk'), ('host', 'dragonstone.org'), ('port', '1234'), > > ('character01', 'Thessalus')] > > > > For a regular list, I could do something like x.index('host') and find > > the index of it, but I don't know how to do this for a tuple where the > > data item isn't known in advance. For example, I want to get the "host" > > entry from the list above; but I can only retrieve it if I know what it > > contains (e.g., x.index(('host', 'dragonstone.org'))). > > > > Is there a better way to do this than a construct similar the following? > > > > for key, value in x: > > if key == 'host': > > print value > > > > If I were you I would use a dictionary for such a thing: > (snipped) The sequence of tuples may have repeated "keys"; if that's the case, then you may use a filter/iterator instead. Using a dictionary would otherwise cause you to lose "values": import itertools mytuple = (('foo', 'bar'), ('foo', 'foobar'), ('baz', 'qux')) it = itertools.ifilter(lambda t : t[0] == 'foo', mytuple) for t in it: print t -- Hope this helps, Steven From chris at kateandchris.net Wed Nov 8 10:25:40 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Wed, 8 Nov 2006 10:25:40 -0500 Subject: Help with installing soappy module on Python 2.4.3 (windows machine) In-Reply-To: <1162913449.381411.261040@k70g2000cwa.googlegroups.com> References: <1162913449.381411.261040@k70g2000cwa.googlegroups.com> Message-ID: <20061108152539.GA32043@kateandchris.net> On Tue, Nov 07, 2006 at 07:30:49AM -0800, ajkadri at googlemail.com wrote: > Hi Folks, > > > I want to install the SOAPpy module on my windows box. I have python > 2.4.3 > > Can you help me with the steps and the URL from where can I get the > download..?? http://pywebsvcs.sourceforge.net/ > > TIA. > > Regards, > Asrarahmed > > -- > http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Sat Nov 11 19:23:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Nov 2006 01:23:59 +0100 Subject: py2exe console removing In-Reply-To: <1163270591.454295.315750@f16g2000cwb.googlegroups.com> References: <1163270591.454295.315750@f16g2000cwb.googlegroups.com> Message-ID: Croteam wrote: > Can somebody tell me how to I remove console at script installing? what does "installing" mean in this context? if the problem is that you get a console window when you run the program without a console (e.g. if you start it from the explorer), use "windows=" instead of "console=" in your setup.py script. From wiggly at wiggly.org Tue Nov 14 10:13:49 2006 From: wiggly at wiggly.org (Nigel Rantor) Date: Tue, 14 Nov 2006 15:13:49 +0000 Subject: modules and generated code In-Reply-To: References: Message-ID: <4559DD2D.6040509@wiggly.org> Peter Otten wrote: > Nigel Rantor wrote: > >> So, if I have a tool that generates python code for me (in my case, >> CORBA stubs/skels) in a particular package is there a way of placing my >> own code under the same package hierarchy without all the code living in >> the same directory structure. > > http://docs.python.org/lib/module-pkgutil.html Ooh, thanks for that. Yep, looks like that should work, but it doesn't. :-/ Do you have any idea whether other __init__.py scripts from the same logical module will still be run in this case? The generated code uses its init script to pull in other code. Off, to tinker some more with this. n From mensanator at aol.com Thu Nov 23 01:37:59 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 22 Nov 2006 22:37:59 -0800 Subject: Abelson and Python In-Reply-To: <1164258788.650158.118150@h54g2000cwb.googlegroups.com> References: <1164239517.067445.179320@e3g2000cwe.googlegroups.com> <1164258788.650158.118150@h54g2000cwb.googlegroups.com> Message-ID: <1164263879.301641.246820@e3g2000cwe.googlegroups.com> Paddy wrote: > bearophileHUGS at lycos.com wrote: > > > While studying the SICP video lectures I have to twist my mind some to > > completely understand the lessons. I implement the programs shown there > > in both Python and Scheme, and I find the Python implementations > > simpler to write (but it's not a fair comparison because I know very > > little Scheme still). > > > > Now some things are changing: > > http://lambda-the-ultimate.org/node/1840 > > > > >The MIT is going to change its curriculum structure that was famous for teaching Scheme in introductory courses. One force behind the reform is no one else than Harold Abelson, famous for his marvelous Scheme opus SICP.< > > >The first four weeks of C1 will be a lot like the first four weeks of 6.001, Abelson said. The difference is that programming will be done in Python and not Scheme.< > > > > > > Someone is translating the SIPC programs in Python too: > > http://www.codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages#Python > > > > With slides and code from lectures: > > http://courses.csail.mit.edu/6.01/ > > http://courses.csail.mit.edu/6.01/fall06/calendar.html > > > > I like Scheme a bit too, but I consider this is a small victory for > > Python :-) > > > > Bye, > > bearophile > > Hi Bearophile. > (Is your name pronounced Beer-owe-file, or Bear-oh-fi-lee, just > wondered :-) ? > > I too have heard about the MIT course changing to Python elsewhere and > wanted to know why it was talked about so much? Scheme was invented at MIT. If Scheme is as fabulous as its adherents claim, why would the institution that invented it drop it? To me, the answer is obvious, but probably not to the press. > I'm from England, I > know that MIT is a very prestigious university, but if Cambridge > changed a course, or better still, The Open University changed a > similar course to Python, I think I'd be hard pressed to hear about it. > Is the MIT course syndicated to Universities around America or > something? > > Cheers, Paddy. From mc_anjo at tamu.edu Fri Nov 3 19:04:05 2006 From: mc_anjo at tamu.edu (Chris Smith) Date: Fri, 03 Nov 2006 18:04:05 -0600 Subject: numpy help In-Reply-To: References: Message-ID: robert wrote: > Chris Smith wrote: > >>Howdy, >> >>I'm a college student and for one of we are writing programs to >>numerically compute the parameters of antenna arrays. I decided to use >>Python to code up my programs. Up to now I haven't had a problem, >>however we have a problem set where we are creating a large matrix and >>finding it's inverse to solve the problem. To invert the matrix I've >>tried using numpy.numarray.linear_algebra.inverse and >>numpy.oldnumeric.linear_algebra.inverse which both give me the same >>error ( I was hoping they called different routines but I think they >>call the same one ). >> > > > try scipy.linalg.inv etc. > > (you are using outdated old NumPy modules with recent array type which sometimes creates type conflicts. > > robert > I tried that one also, and it didn't work. Chris From steve at REMOVEME.cybersource.com.au Tue Nov 21 23:33:02 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 22 Nov 2006 15:33:02 +1100 Subject: Is there a list comprehension for this? References: <1164143944.874745.19470@f16g2000cwb.googlegroups.com> Message-ID: On Tue, 21 Nov 2006 13:19:04 -0800, liam_herron wrote: > > Given: > dw = [ 1, -1.1, +1.2 ] > > Suppose I want to create a list 'w' that is defined as > > w[0] = dw[0], > w[1] = w[0] + dw[1], > w[2] = w[1] + dw[2] > > Is there a list comprehension or map expression to do it in one or 2 > lines. This isn't a list comp and it doesn't need map, but if you absolutely have to have a one-liner: w = [dw[0], dw[0] + dw[1], dw[0] + dw[1] + dw[2]] Obviously that doesn't scale at all to larger lists, but it gives you a better idea: replace the manual additions with sum(). w = [sum(dw[0:i]) for i in range(1, len(dw))] but if your dw list is huge, you're spending a lot of time slicing dw and adding up the same numbers over and over again. (This doesn't matter if dw is small, but could become expensive if dw is huge.) Which leads to the next version: def running_sum(dw): """Return a list of the running sums of sequence dw""" rs = [0]*len(dw) for i in range(len(dw)): rs[i] = dw[i] + rs[i-1] return rs It isn't a one-liner, but it is clear, the name is self-documenting, it has a doc-string, you don't have to copy-and-paste code every time you want to use it, and now that you've defined it once, you can use it as a one-liner as many times as you like. >>> running_sum(range(5)): [0, 1, 3, 6, 10] -- Steven D'Aprano From sjmachin at lexicon.net Mon Nov 6 19:46:46 2006 From: sjmachin at lexicon.net (John Machin) Date: 6 Nov 2006 16:46:46 -0800 Subject: auto indent References: Message-ID: <1162860406.301935.127110@m7g2000cwm.googlegroups.com> M.N.Smadi wrote: > Hi there; > > i have a script that is not indented properly. Is there a way that i can > have it auto indented. It depends on what you mean by "not indented properly". Indentation is part of the Python grammar. If the script compiles OK, and works as expected, but you have (say) 4-space indent in parts, and 3-space in other parts, or a mixture of tabs and spaces, you could use the supplied reindent script. It's C:\Python25\Tools\Scripts\reindent.py on my machine. Do read the documentation at the start of the script before you run it. If you mean that the indentation is just plain wrong, such that the script will not compile without error, or incorrect indentation of one or more lines is causing incorrect results, then you will have to fix it manually. There is no "artificial intelligence" that can work out what the indentation should be. HTH, John From steve at holdenweb.com Mon Nov 13 03:25:04 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Nov 2006 02:25:04 -0600 Subject: MemoryError In-Reply-To: <5a00f6240611121010i63c16d95tf9fc743edcb58ebf@mail.gmail.com> References: <5a00f6240611121010i63c16d95tf9fc743edcb58ebf@mail.gmail.com> Message-ID: Bugra Cakir wrote: > Hi, > > Within a Python program how can we avoid getting "MemoryError" problem ? > Well that depends why you are getting it in the first place. If you can post the traceback your program prints out then you might get some specific advice for the current case. The usual advice might be "don't use too much memory", but that alone probably won't be helpful. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jack at abc.net Sat Nov 18 17:23:42 2006 From: jack at abc.net (Michael Press) Date: Sat, 18 Nov 2006 22:23:42 GMT Subject: syntax error in sum(). Please explicate. Message-ID: I have not written python codes nor run any. I saw this code posted and decided to try it. It fails. I read the tutorial and the entry for the built in function sum, but still do not see the problem. The code was cut and paste. Please help. Thanks. _________________________BEGIN_CODE_________________________ #!/usr/bin/python ps = [none, 2,3,5,7,11,13,17,19,23,29] def phi(x, a): return x - sum(phi(x // ps[i+1], i) for i in range(a)) def pi(n): from math import sqrt if n <= 1: return 0 a = pi(int(sqrt(n))) return phi(n, a) + a - 1 __________________________END_CODE__________________________ Here is the result of running it: File "/Users/mdp/source/prime_counter_python", line 6 return x - sum(phi(x // ps[i+1], i) for i in range(a)) ^ SyntaxError: invalid syntax Here are some lines from python -v: Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information -- Michael Press From jimvtess at gmail.com Sat Nov 4 12:18:11 2006 From: jimvtess at gmail.com (Jim) Date: 4 Nov 2006 09:18:11 -0800 Subject: win32file.DeviceIoControl(FSCTL_GET_RETRIEVAL_POINTERS) Message-ID: <1162660691.829676.85990@h48g2000cwc.googlegroups.com> I'm not sure how to perform this operation in Python. The difficulty is in knowing the size of the output buffer: if it is too small, I get an "insufficient buffer" exception; too large, and I get an "end of file" exception. In neither case is any partial data available. I'd rather not resort to a binary seach... From gregpinero at gmail.com Wed Nov 8 14:56:14 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Wed, 8 Nov 2006 14:56:14 -0500 Subject: PIL - Pixel Level Image Manipulation? In-Reply-To: <312cfe2b0611080853x5e388fbfpb04f2bdb811eafa6@mail.gmail.com> References: <312cfe2b0611080853x5e388fbfpb04f2bdb811eafa6@mail.gmail.com> Message-ID: <312cfe2b0611081156v619bd82eu782b068bfd2cf558@mail.gmail.com> On 11/8/06, Gregory Pi?ero wrote: > I want to be able to randomly change pixels in an image and view the > results. I can use whatever format of image makes this easiest, e.g., > gray scale, bit tonal, etc. > > Ideally I'd like to keep the pixels in an intermediate format like a > list of (integers?) or an array and convert that to an image as > needed. > > I'm hoping someone has some experience on this and could offer some > advice or code. I thought it would be easy in PIL but I'm not sure. I did find these functions after more searching: http://mail.python.org/pipermail/image-sig/2002-July/001914.html Perhaps I'll try those out tonight if I don't hear of anything better in the meantime. -Greg From tleeuwenburg at gmail.com Wed Nov 1 23:43:31 2006 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 1 Nov 2006 20:43:31 -0800 Subject: The Python Journal Message-ID: <1162442611.407124.154980@e3g2000cwe.googlegroups.com> To whom it may concern, I have been involved in putting together a new Python journal, called (oh so originally) The Python Journal. This isn't related to a previous project also called The Python Journal although we have the approval of the group that put it together in using their name. http://pyjournal.cgpublisher.com is the journal URL, and it has a number of news feeds -- blog entries, new products (i.e. articles and volumes) and product reviews (not used currently). We'd love it if you could have a look at our first issue, and let us know what you think! Cheers, -T (editor-in-chief) From walterbyrd at iname.com Thu Nov 2 10:08:31 2006 From: walterbyrd at iname.com (walterbyrd) Date: 2 Nov 2006 07:08:31 -0800 Subject: is mod_python borked? Message-ID: <1162480110.992783.267620@e3g2000cwe.googlegroups.com> I am considering python, instead of php, for web-application development. I often see mod_python.criticisized as being borked, broken, or just plain sucking. Any truth to any of that? From mike at hobbshouse.org Fri Nov 10 16:18:55 2006 From: mike at hobbshouse.org (Michael Hobbs) Date: Fri, 10 Nov 2006 15:18:55 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <4554D416.70408@hobbshouse.org> Message-ID: <4554ECBF.7040603@hobbshouse.org> Ron Adam wrote: > It is also an outline form that frequently used in written languages. Something > python tries to do, is to be readable as if it were written in plain language > where it is practical to do so. So the colon/outline form makes a certain sense > in that case as well. > That is perhaps the most convincing argument that I've heard so far. Indeed, I often find myself writing out colons when writing pseudo-code out on paper. The reason, however, is usually because my indents don't quite line up as perfectly on paper as they do in an editor. The colons provide a form of backup separation for when my columns start to get sloppy. (Natural language is actually filled with such redundancies in order to compensate for sloppy handwriting.) This backup function obviously isn't needed when a computer is taking care of the layout. My final argument against the colons is to simply try programming in Ruby for a while and then come back to Python. I think you'll find that programming without the colons just simply feels more "natural". - Mike From email at christoph-haas.de Thu Nov 23 09:20:44 2006 From: email at christoph-haas.de (Christoph Haas) Date: Thu, 23 Nov 2006 15:20:44 +0100 Subject: Email headers and non-ASCII characters In-Reply-To: <200611231512.33779.email@christoph-haas.de> References: <200611231512.33779.email@christoph-haas.de> Message-ID: <200611231520.44611.email@christoph-haas.de> On Thursday 23 November 2006 15:12, I wrote: > My example code: > > ================================= > def sendmail(sender, recipient, body, subject): > message = MIMEText(body) > message['Subject'] = Header(subject, 'iso-8859-1') > message['From'] = Header(sender, 'iso-8859-1') > message['To'] = Header(recipient, 'iso-8859-1') > > s = smtplib.SMTP() > s.connect() > s.sendmail(sender, recipient, message.as_string()) > s.close() > ================================= Just for completeness - of course I imported the Header methods from here: from email.MIMEText import MIMEText from email.Header import Header Christoph From ptmcg at austin.rr._bogus_.com Mon Nov 27 13:41:23 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 27 Nov 2006 18:41:23 GMT Subject: can't get cgi values References: <1164652134.826957.80980@h54g2000cwb.googlegroups.com> Message-ID: form("citation").value Is form some form of dict? If so, then this should be something like: form["citation"] If not, then maybe value is a function, requiring ()'s to actually invoke it. -- Paul From jorge.vargas at gmail.com Wed Nov 8 00:51:03 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Wed, 8 Nov 2006 01:51:03 -0400 Subject: Python memory usage In-Reply-To: <1162964551.328495.211090@f16g2000cwb.googlegroups.com> References: <1162964551.328495.211090@f16g2000cwb.googlegroups.com> Message-ID: <32822fe60611072151s6b1bf5f1u42a77e938f97462d@mail.gmail.com> On 7 Nov 2006 21:42:31 -0800, placid wrote: > Hi All, > > Just wondering when i run the following code; > > for i in range(1000000): > print i > the problem of that is that all the memory is used by the list returned by range which wont be freed until the for loop exits try this >>> import itertools >>> for i in itertools.count(1000000): ... print i that uses an iterator which I believe will bring down the memory usage but will kill your CPU :) > the memory usage of Python spikes and when the range(..) block finishes > execution the memory usage does not drop down. Is there a way of > freeing this memory that range(..) allocated? > > I found this document but the fix seems too complicated. > > http://www.python.org/pycon/2005/papers/79/python-memory.pdf > > Cheers > > -- > http://mail.python.org/mailman/listinfo/python-list > From Sebastien.Boisgerault at gmail.com Fri Nov 17 14:38:02 2006 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 17 Nov 2006 11:38:02 -0800 Subject: About alternatives to Matlab In-Reply-To: <1163713573.147702.229320@k70g2000cwa.googlegroups.com> References: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> <1163711343.870829.110030@h48g2000cwc.googlegroups.com> <1163713573.147702.229320@k70g2000cwa.googlegroups.com> Message-ID: <1163792282.802768.216630@m73g2000cwd.googlegroups.com> On Nov 16, 10:46 pm, "John Henry" wrote: > Bill Gates will have you jailed! :-) > > On a more serious note, is there any alternative to Simulink though? Ptolemy II. Java stuff in the core but components may be written in Python http://ptolemy.eecs.berkeley.edu/ptolemyII/ http://ptolemy.eecs.berkeley.edu/ptolemyii/ptII5.0/ptII/doc/codeDoc/ptolemy/actor/lib/python/PythonScript.htm > sturlamolden wrote: > >and is infinitely > > more expensive. > > > Does anyone wonder why I am not paying for Matlab maintenance anymore? > > > Sorry Mathworks, I have used your product for years, but you cannot > > compete with NumPy. > > > Cheers, > > Sturla Molden From samantha7395 at hotmail.com Thu Nov 16 19:39:48 2006 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 16 Nov 2006 16:39:48 -0800 Subject: Writing to Registry References: Message-ID: Thanks for the link. S "Gabriel Genellina" wrote in message news:mailman.295.1163723213.32031.python-list at python.org... > At Thursday 16/11/2006 20:48, Samantha wrote: > >>I am working with this recipes: >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66011 >> >>The problem I am having is setting a hex value. >>This line --- SetValueEx(aKey,"MyNewKey",0, REG_SZ, >>r"c:\winnt\explorer.exe") >>I want something Like -- SetValueEx(aKey,"MyNewSize",0, REG_SZ, 120 or >>some value) > > Usually when you don't know how to use a certain function, you begin by > reading the documentation for it: > http://docs.python.org/lib/module--winreg.html#l2h-5827 > > > -- > Gabriel Genellina > Softlab SRL > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu > cuenta ya! - http://correo.yahoo.com.ar From bearophileHUGS at lycos.com Thu Nov 23 14:56:46 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 23 Nov 2006 11:56:46 -0800 Subject: python gaining popularity according to a study In-Reply-To: <1164306918.845529.95820@f16g2000cwb.googlegroups.com> References: <1164306918.845529.95820@f16g2000cwb.googlegroups.com> Message-ID: <1164311806.482272.303410@e3g2000cwe.googlegroups.com> ccdetail at gmail.com: > Python is the 7th most commonly used language, up from 8th. > The only one gaining ground besides VB in the top 10. It also shows that Ruby is gaining even more, and D is (gladly) growing too. Bye, bearophile From fredrik at pythonware.com Tue Nov 28 06:30:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 28 Nov 2006 12:30:07 +0100 Subject: "fork and exit" needed? In-Reply-To: References: <8osmm21skionildtnme1j0nvqbla6oqk72@4ax.com> Message-ID: Nick Craig-Wood wrote: > If you run this > > import os,sys,time > print os.getpid() > sys.stdout = open(os.devnull, 'w') > time.sleep(60) > > It prints its pid. and not only that, if you run print "world", print "hello" it prints "hello world" in the wrong order! From Anthon.van.der.Neut at googlemail.com Tue Nov 14 07:31:52 2006 From: Anthon.van.der.Neut at googlemail.com (Anthon) Date: 14 Nov 2006 04:31:52 -0800 Subject: Python 2.5 Core Dump on Solaris 8 In-Reply-To: <1163506137.477368.111160@h48g2000cwc.googlegroups.com> References: <1163506137.477368.111160@h48g2000cwc.googlegroups.com> Message-ID: <1163507512.678945.246560@m7g2000cwm.googlegroups.com> You can set an environment variable MALLOC_CHECK_ to influence the behaviour of glibc 0 -> no error message program continues 1 -> error message, program continues 2 -> no error message, kills program 3 -> error message, kills program Since the message only occured with my two programs at exit time, I set the environment var to 0 HTH Anthon From gregpinero at gmail.com Wed Nov 8 11:53:22 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Wed, 8 Nov 2006 11:53:22 -0500 Subject: PIL - Pixel Level Image Manipulation? Message-ID: <312cfe2b0611080853x5e388fbfpb04f2bdb811eafa6@mail.gmail.com> I want to be able to randomly change pixels in an image and view the results. I can use whatever format of image makes this easiest, e.g., gray scale, bit tonal, etc. Ideally I'd like to keep the pixels in an intermediate format like a list of (integers?) or an array and convert that to an image as needed. I'm hoping someone has some experience on this and could offer some advice or code. I thought it would be easy in PIL but I'm not sure. Much Appreciated, -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) From tim.peters at gmail.com Fri Nov 17 19:50:43 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 17 Nov 2006 19:50:43 -0500 Subject: Decimal() instead of float? In-Reply-To: References: <1163294604.4675.4.camel@pepper> <1163511997.4675.88.camel@pepper> <4559F828.7070704@holdenweb.com> <1163794251.5107.151.camel@pepper> <1163800304.5107.179.camel@pepper> Message-ID: <1f7befae0611171650h2ae00970g2f5a5d10ea2b73c3@mail.gmail.com> [Michael B. Trausch] >> Let's say that I want to work with the latitude 33.6907570. In Python, >> that number > can not be stored exactly without the aid of >> decimal.Decimal(). >> >> >>> 33.6907570 >> 33.690756999999998 >> >>> >> >> As you can see, it loses accuracy after the 6th decimal place. [Terry Reedy] > No, it loses accuracy in the 15th decimal place, which is the 17th digit. > This is far more accurate than any measured latitude could be. > If the above is a measurement, it represents anything from 33.69075695 > to 33.69075705. The conversion error would have to be multiplied by some > number of millions before it would be visible in the 7th decimal place > (your last). > > Any trigonometric calculations will use an *approximate* value of pi and > polynomial *approximations* of the theoretical functions. The trend in "modern" math libraries is actually that sin(), cos() and tan() return a result strictly less than 1 ULP off from the true mathematical result (including "acting as if" they used an infinitely precise value for pi). It remains unclear what actual benefit there is in, e.g., treating a sloppy argument like 2.31e273 "as if" it were infinitely precise and reducing it by an infinitely precise value of pi, /except/ that it allows making precise statements about the accuracy of functions doing so. In effect, this way all the blame gets pinned on the user if they don't like the results ;-) > Perhaps you have been given impossible conditions to fulfill. I'm sure it's inconceivable to any programmer that management would have an unreasonable expectation. From gagsl-py at yahoo.com.ar Thu Nov 9 21:01:25 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 09 Nov 2006 23:01:25 -0300 Subject: pack a three byte int In-Reply-To: <1163121855.884088.12970@h48g2000cwc.googlegroups.com> References: <1163027401.386603.263030@k70g2000cwa.googlegroups.com> <1163121855.884088.12970@h48g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20061109225427.0595fe40@yahoo.com.ar> At Thursday 9/11/2006 22:24, p.lavarre at ieee.org wrote: >Perhaps Python can't concisely say three-byte int ... > >But Python can say six-nybble hex: > > >>> import binascii > >>> cdb = binascii.unhexlify('%02X%06X%02X%02X' % (0x08, 0x12345, 0x80, 0)) > >>> binascii.hexlify(cdb) >'080123458000' The only problem I can see is that this code is endianness-dependent; the suggested versions using pack(">...") not. But this may not be of concern to you. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From rtw at freenet.co.uk Fri Nov 3 11:52:32 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Fri, 03 Nov 2006 10:52:32 -0600 Subject: Tools for Java/Python scripting References: <1162569614.650081.166270@h48g2000cwc.googlegroups.com> Message-ID: wrote in news:mailman.1722.1162571941.11739.python-list at python.org in comp.lang.python: > > steve> http://wiki.python.org/moin/Java_Scripting > > Renamed to "JavaScripting". > > Skip So nobody around here has heared of that other language called JavaScript then ? Perhaps "Scripting_Java" might be better. Pythoning-ly yr's Rob. -- http://www.victim-prime.dsl.pipex.com/ From stanc at al.com.au Thu Nov 16 23:48:24 2006 From: stanc at al.com.au (Astan Chee) Date: Fri, 17 Nov 2006 15:48:24 +1100 Subject: popen(1-4) as a seperate process Message-ID: <455D3F18.40902@al.com.au> Hi, Im trying to popen (or more specifically os.popen4() ) from wxPython. I've read the documentation on popen and it says I can do a popen as a seperate process or popen not as a child process but it doesnt say how. Can anyone help? Thanks From aspmanualator_1234567890 at yahoo.com Mon Nov 27 02:07:34 2006 From: aspmanualator_1234567890 at yahoo.com (Asper Faner) Date: 26 Nov 2006 23:07:34 -0800 Subject: I am looking xml-python processor Message-ID: <1164611254.056063.23110@l39g2000cwd.googlegroups.com> Is there any newer version of topic map processor I can use ? Thanks From bignose+hates-spam at benfinney.id.au Wed Nov 8 20:17:15 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 09 Nov 2006 12:17:15 +1100 Subject: python Error: IndentationError: expected an indented block References: <20061108142618.77660.qmail@web58114.mail.re3.yahoo.com> Message-ID: <87bqnhmnac.fsf@benfinney.id.au> Please don't post HTML message bodies to a public forum. Antonios Katsikadamos writes: > hi all. I am using python 2.4. I have to run an older python code > and when i run it i get the following message > IndentationError: expected an indented block. > 1)what does this mean? It's self-explanatory. There's an error in the indentation; Python was expecting an indented block, but didn't get one. > 2)how can i overcome this problem Fix the indentation. As you probably know, in Python, indentation is syntactically significant information to both the programmer and to the interpreter. If that information is lost, Python can't know what was meant, and refuses to guess. Probably something has mangled the white-space in the program file. Either fix it manually, or go back to a more canonical form of the file and see if it's been altered. -- \ "I have a large seashell collection, which I keep scattered on | `\ the beaches all over the world. Maybe you've seen it." -- | _o__) Steven Wright | Ben Finney From rpdooling at gmail.com Wed Nov 8 10:49:44 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 8 Nov 2006 07:49:44 -0800 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: <4551FA0F.4000202@hotmail.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> <4551FA0F.4000202@hotmail.com> Message-ID: <1163000984.575289.87230@i42g2000cwa.googlegroups.com> Chaz Ginger wrote: >> it is supposed to be about PYTHON. Get it? I agree. And Python is an extremely serious matter calling for decorum and propriety. Don't say fuck, ni, peng, or ni-wom. http://en.wikipedia.org/wiki/Knights_who_say_Ni rd From ptmcg at austin.rr._bogus_.com Sun Nov 26 12:59:39 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 26 Nov 2006 17:59:39 GMT Subject: RuPy Ruby & Python Conference 2007 References: <1164558164.421675.302290@14g2000cws.googlegroups.com> Message-ID: "Katarzyna Bylec" wrote in message news:1164558164.421675.302290 at 14g2000cws.googlegroups.com... > Hello, > > we would like to invite you to one of the biggest Ruby and Python > events in > central-eastern Europe next year. RuPy Conference dedicated to Ruby and > Python programming languages will take place in April 14-15, 2007 in > Poznan, > Poland and the idea behind it is to put together experts with young > programmers and to support a good communication channel for East-West > exchange of prospective ideas. > Isn't this the week after the: Oil and Water Conference Gasoline and Dynamite Conference Hatfield and McCoy Symposium -- Paul From olakh at walla.co.il Sat Nov 25 16:39:55 2006 From: olakh at walla.co.il (Ola K) Date: 25 Nov 2006 13:39:55 -0800 Subject: a -very- case sensitive search Message-ID: <1164490795.866046.133230@45g2000cws.googlegroups.com> Hi, I am pretty new to Python and I want to make a script that will search for the following options: 1) words made of uppercase characters -only- (like "YES") 2) words made of lowercase character -only- (like "yes") 3) and words with only the first letter capitalized (like "Yes") * and I need to do all these considering the fact that not all letters are indeed English letters. I went through different documention section but couldn't find a right condition, function or method for it. Suggestions will be very much appriciated... --Ola From fredrik at pythonware.com Mon Nov 13 05:03:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Nov 2006 11:03:09 +0100 Subject: Data structure for ordered sequence In-Reply-To: <1163411468.025376.171210@k70g2000cwa.googlegroups.com> References: <1163410449.081226.49270@i42g2000cwa.googlegroups.com> <1163411468.025376.171210@k70g2000cwa.googlegroups.com> Message-ID: Eric_Dexter at msn.com wrote: > unless this is homework because the pil people will not let > you distribute pils. I'm not sure I can parse this sentence fragment. What do you mean? From fuzzyman at gmail.com Mon Nov 27 15:55:41 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 27 Nov 2006 12:55:41 -0800 Subject: Calling a thread asynchronously with a callback In-Reply-To: <4t0nr6F110supU1@mid.uni-berlin.de> References: <4t0nr6F110supU1@mid.uni-berlin.de> Message-ID: <1164660941.428985.262350@l12g2000cwl.googlegroups.com> Diez B. Roggisch wrote: > Edwin Gomez wrote: > > > I'm a C# developer and I'm new to Python. I would like to know if the > > concept of Asynchronous call-backs exists in Python. Basically what I > > mean is that I dispatch a thread and when the thread completes it invokes > > a method from the calling thread. Sort event driven concept with threads. > > Counter question: does such a thing exist in C#, and if, is it bound to some > existing event loop? > > I'm really curious, because having code being interrupted at any time by a > asynchronous callback strikes me as dangerous. But then maybe I'm just a > whimp :) > I've used them with Windows Forms,. The callback puts a message in the event loop. It doesn't actually interrupt the code. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Diez From aisaac at american.edu Sat Nov 11 16:11:38 2006 From: aisaac at american.edu (Alan Isaac) Date: Sat, 11 Nov 2006 21:11:38 GMT Subject: handling many default values References: Message-ID: "Steven D'Aprano" wrote > (1) If there really is no alternative to a class with many arguments; > (2) and instances can vary those arguments unpredictably; > then this approach seems reasonable to me. But I really suggest you > rethink your class design. Thanks to all who replied and to George for his specific example. Steve's comments seem to summarize the overall sentiment: there is no *general* objection, but I should make sure my specific implementation really profits from a parameter holding class (rather than, e.g., a super class in which appropriate defaults are set). I believe this is the case, since the many parameters can vary arbitrarily and do not fall into neat groupings. Also, as an aside, no one objected to using self.__dict__.update(kwargs) in the __init__ function of the parameter holding class. Thanks, Alan From larry.bates at websafe.com Fri Nov 3 16:32:36 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 03 Nov 2006 15:32:36 -0600 Subject: py2exe questions In-Reply-To: References: Message-ID: <454BB574.9030607@websafe.com> Doug Stell wrote: > I have 2 questions about py2exe or any similar utility. > > 1. Is it possible to create a single Windows executable that does not > blow out to a folder full of files and can be called from scripts > using command line arguments? > > 2. If the above can be done, it is possible to hide parts of the > Python source code from users? These users are software developers, > but we don't want them to see how the code does what it does. > > thanks, doug py2exe reduce the number of files you need to distribute down to 4: msvcr71.dll w9xpopen.exe (Windows/98 support) library.zip (all .pyo, .pyd, and .dll files) applcation.exe I does not however go to great lengths to "hide" the code from someone with time/expertise that wants to get to your code (but then just about anything can be disassembled). The compiled .pyo files are just placed in library.zip. At least it doesn't send your .py files along. -Larry From insyte at gmail.com Tue Nov 14 11:41:11 2006 From: insyte at gmail.com (insyte at gmail.com) Date: 14 Nov 2006 08:41:11 -0800 Subject: __cmp__ between dissimilar objects In-Reply-To: References: <1163464397.679361.215050@m7g2000cwm.googlegroups.com> Message-ID: <1163522471.707278.178600@e3g2000cwe.googlegroups.com> > When the rich comparison methods raise NotImplementedError, the > comparison logic inside the interpreter tries reversing the operands. Can you point me to a description of this algorithm? It doesn't seem to be described in the documentation for the rich comparison or __cmp__ methods... -Ben From adrian.casey at internode.on.net Tue Nov 14 04:30:16 2006 From: adrian.casey at internode.on.net (Adrian Casey) Date: Tue, 14 Nov 2006 19:00:16 +0930 Subject: Using signal.alarm to terminate a thread References: <12lgk7h55lu0vb4@corp.supernews.com> Message-ID: <12lj35aqa9drd8a@corp.supernews.com> Nick Craig-Wood wrote: > Adrian Casey wrote: >> I have a multi-threaded python application which uses pexpect to connect >> to >> multiple systems concurrently. Each thread within my application is a >> connection to a remote system. The problem is when one of the child >> threads runs a command which generates an unlimited amount of output. >> The >> classic example of this is the "yes" command. If you >> execute "pexpect.run('yes')", your cpu will sit at 100% forever. >> >> Here is a simple multi-threaded program using pexpect which demonstrates >> the >> problem. The command 'yes' is run in a thread. The parent says that >> when >> the alarm goes off, run the handler function. The thread sets the alarm >> to trigger after 5 seconds. > > 1) Don't ever mix threads and signals - you are heading for trouble! > > 2) pexpect has a timeout parameter exactly for this case > > import os, pexpect, threading > > def runyes(): > print "Running yes command..." > pexpect.run('yes', timeout=5) > > t = threading.Thread(target=runyes) > t.start() > t.join() > The timeout parameter will not work in this case. If you run the sample code above, it will run forever. The 'yes' command presents a class of command which can not be easily be handled by pexpect. As far as I know, mixing threads and signals is OK provided the parent creates the alarm. Adrian. From jan.danielsson at gmail.com Thu Nov 30 23:32:26 2006 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Fri, 01 Dec 2006 05:32:26 +0100 Subject: UTF8 & HTMLParser Message-ID: <456faf5e$1@griseus.its.uu.se> Hello all, I'm writing a python script which fetches a HTML-page (using wget), and then parses the retrieved page using a custom htmllib HTMLParser. The page I fetch is encoded in utf8, and my text-handler currently looks like this: def handle_data(self, text): if self.inOption: self.currentName = text However, I would like to convert the "text" (which is utf8) to latin-1. How do I do that? I've been trying to figure it out for some time now, and I'm just getting frustrated. :-( -- Kind Regards, Jan Danielsson Te audire non possum. Musa sapientum fixa est in aure. From sjmachin at lexicon.net Mon Nov 6 15:56:04 2006 From: sjmachin at lexicon.net (John Machin) Date: 6 Nov 2006 12:56:04 -0800 Subject: Unicode/ascii encoding nightmare In-Reply-To: References: <1162842650.780517.180360@b28g2000cwb.googlegroups.com> Message-ID: <1162846564.782883.259110@h54g2000cwb.googlegroups.com> Robert Kern wrote: > However, I don't know of an encoding that takes u"f?dselsdag" to > 'f\xc3\x83\xc2\xb8dselsdag'. There isn't one. C3 and C2 hint at UTF-8. The fact that C3 and C2 are both present, plus the fact that one non-ASCII byte has morphoploded into 4 bytes indicate a double whammy. Cheers, John From johnjsal at NOSPAMgmail.com Wed Nov 8 16:42:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Nov 2006 16:42:50 -0500 Subject: is this the right way to do subclasses? In-Reply-To: References: <45522074$0$17101$c3e8da3@news.astraweb.com> Message-ID: <45524f40$0$32365$c3e8da3@news.astraweb.com> Peter Otten wrote: > You may need a no-op implementation of fix_attributes() in the Character > class. What does that mean? Is that in case I use Character directly to create an object? Would that just be a 'pass' statement? From rridge at csclub.uwaterloo.ca Sun Nov 19 22:13:30 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 19 Nov 2006 19:13:30 -0800 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? References: <18c54$455d019b$59ad1aca$24364@news.flashnewsgroups.com> <455d507d$0$18480$9b622d9e@news.freenet.de> <3188c$455d923f$59ad1aca$4742@news.flashnewsgroups.com> <455E5D15.7030207@v.loewis.de> <3e540$4560b958$59ad1aca$32456@news.flashnewsgroups.com> <4560E3AE.5030307@v.loewis.de> Message-ID: <1163992410.229236.60830@e3g2000cwe.googlegroups.com> Martin v. L?wis wrote: > One approach I had been considering is to always make the decoding > succeed, by using the private-use-area of Unicode to represent bytes > that don't decode correctly. That would conflict with private use characters appearing in file names. Personally, I think os.listdir() should return the file names only in Unicode if they're actually stored that way in the underlying file system (eg. NTFS), otherwise return them as byte strings. I doubt anyone in this thread would like that, though. Ross Ridge From beliavsky at aol.com Tue Nov 14 10:07:53 2006 From: beliavsky at aol.com (Beliavsky) Date: 14 Nov 2006 07:07:53 -0800 Subject: Programmatically finding "significant" data points References: <1163513101.580610.151420@b28g2000cwb.googlegroups.com> Message-ID: <1163516873.105244.80870@e3g2000cwe.googlegroups.com> erikcw wrote: > Hi all, > > I have a collection of ordered numerical data in a list. Called a "time series" in statistics. > The numbers > when plotted on a line chart make a low-high-low-high-high-low (random) > pattern. I need an algorithm to extract the "significant" high and low > points from this data. > > Here is some sample data: > data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, > 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, > 0.10] > > In this data, some of the significant points include: > data[0] > data[2] > data[4] > data[6] > data[8] > data[9] > data[13] > data[14] > .... > > How do I sort through this data and pull out these points of > significance? The best place to ask about an algorithm for this is not comp.lang.python -- maybe sci.stat.math would be better. Once you have an algorithm, coding it in Python should not be difficult. I'd suggest using the NumPy array rather than the native Python list, which is not designed for crunching numbers. From python.list at tim.thechases.com Fri Nov 3 13:50:07 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 03 Nov 2006 12:50:07 -0600 Subject: ANN: SE 2.3. Available now In-Reply-To: <454B8B8D.8010406@vtxmail.ch> References: <454B3B49.6070702@vtxmail.ch> <454B6FEC.20709@islandtraining.com> <454B8B8D.8010406@vtxmail.ch> Message-ID: <454B8F5F.5050907@tim.thechases.com> > nah, if you've spent more than five minutes on c.l.python lately, you'd > noticed that it's the Solution to Everything (up there with pyparsing, I > think). SE would be the Solution to Everything. pyparsing Provides Your Perfect Alternative where Regexp Syntax Is No Good. The "re" module is just Routinely Expected to solve all problems. :) -tkc From bj_666 at gmx.net Thu Nov 9 11:32:27 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 09 Nov 2006 17:32:27 +0100 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> Message-ID: In , Michael Hobbs wrote: > Python is already sensitive to whitespace and the newline anyway, so why > not put it to good use? For example, Python rejects this statement > because of the newline present: > if self.hungry or > self.depressed: > self.eat() > You need to use the backslash to continue the expression on the next line: > if self.hungry or \ > self.depressed: > self.eat() You don't need the backslash if you use parenthesis: if (self.hungry or self.depressed): self.eat() > I think the colon could be omitted from every type of compound > statement: 'if', 'for', 'def', 'class', whatever. Am I missing anything? I would miss auto-indenting in my editor to which the colon at the line end is an important clue. Ciao, Marc 'BlackJack' Rintsch From laurent.pointal at limsi.fr Tue Nov 21 10:56:18 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 21 Nov 2006 16:56:18 +0100 Subject: Software Compatable with other versions? In-Reply-To: <1164113768.450227.161750@m73g2000cwd.googlegroups.com> References: <1164113768.450227.161750@m73g2000cwd.googlegroups.com> Message-ID: georgeryoung at gmail.com a ?crit : > On Nov 21, 7:24 am, "Michael Yanowitz" wrote: >> I am still using Python 2.4.3, I haven't upgraded yet. >> However, I would like to know if my 2.4.3 programs will run >> in 2.5 without modification. >> Is there any way to test that my software is compatable >> with 2.5 (or any other version), without actually installing >> that version?: > You need to install 2.5. If you're on linux or similar OS, get the > source and > do > ./configure > make altinstall > This installs almost everything, but does not overwrite your link to > 2.4.3. > > Then you can test your code using > python2.5 myfile.py > > When you're all set, just change the link "python" to point to the new > python2.5. Hum, IMHO it's a bad idea to change the python link to another Python version (other than de distro default). Can put the Python version in script header (and make it executable) #!/bin/env python2.5 Can write a small script shell starting the Python script with the ad-hoc Python version. >> I have been told that the .pyc are not compatable. Is it >> possible, to convert a 2.4.x .pyc to a 2.5 .pyc? The magic code. Just rm -rf *.pyc from your own scripts directories, they will be rebuilt. A+ Laurent. From phil at riverbankcomputing.co.uk Sun Nov 5 08:11:21 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 5 Nov 2006 13:11:21 +0000 Subject: ANN: SIP v4.5 Released Message-ID: <200611051311.21536.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of SIP v4.5 available from http://www.riverbankcomputing.co.uk/sip/. SIP is a tool for generating Python modules that wrap C or C++ libraries. It is similar to SWIG. It is used to generate PyQt and PyKDE. Full documentation is available at http://www.riverbankcomputing.com/Docs/sip4/sipref.html. SIP is licensed under the Python License and runs on Windows, UNIX, Linux and MacOS/X. SIP requires Python v2.3 or later. The main focus of this release is support for Python v2.5. Other features of SIP include: - extension modules are implemented as a single binary .pyd or .so file (no Python stubs) - support for Python new-style classes - generated modules are quick to import, even for large libraries - support for Qt's signal/slot mechanism - thread support - the ability to re-implement C++ abstract and virtual methods in Python - the ability to define Python classes that derive from abstract C++ classes - the ability to spread a class hierarchy across multiple Python modules - support for C++ namespaces - support for C++ exceptions - support for C++ operators - an extensible build system written in Python that supports over 50 platform/compiler combinations - the generation of API files for IDEs that support autocompletion and call tips. Phil From st911 at rock.com Thu Nov 30 11:44:23 2006 From: st911 at rock.com (st911 at rock.com) Date: 30 Nov 2006 08:44:23 -0800 Subject: *** Rogue OFFICIAL Bastards DEFAME the NAME of UNITED STATES of AMERICA *** Message-ID: <1164905063.492726.115630@f1g2000cwa.googlegroups.com> The written apology reads: "The United States of America apologizes to Mr. Brandon Mayfield and his family for the suffering caused by the FBI's misidentification of Mr. Mayfield's fingerprint and the resulting investigation of Mr. Mayfield, including his arrest as a material witness in connection with the 2004 Madrid train bombings and the execution of search warrants and other court orders in the Mayfield family home and in Mr. Mayfield's law office." He and his family later sued the U.S. government for damages. "We lived in 1984," Mayfield told reporters Wednesday. "I'm talking about the George Orwell, frightening brave new world in which Big Brother is constantly watching you." (Watch Mayfield discuss the case Video) "I, myself, have dark memories of stifling paranoia, of being monitored, followed, watched, tracked," he said, choking back emotion. "I've been surveilled, followed, targeted primarily because I've been an outspoken critic of this administration and doing my job to defend others who can't defend themselves, to give them their day in court, and mostly for being a Muslim." The government refused, he said, to tell him where they put their cameras and surveillance devices, leaving his family wondering if their private conversations and intimate moments were on display. "The days and weeks and months following my arrest were some of the hardest and darkest that myself and my family have ever had to endure," he said. "And all because of this government's ill-conceived war on terror. ... What I really want is for this not to happen to anyone else." Wednesday's settlement includes not only a $2 million payment and an apology, but also an agreement by the government to destroy communications intercepts conducted by the FBI against Mayfield's home and office during the investigation. The written apology reads: "The United States of America apologizes to Mr. Brandon Mayfield and his family for the suffering caused by the FBI's misidentification of Mr. Mayfield's fingerprint and the resulting investigation of Mr. Mayfield, including his arrest as a material witness in connection with the 2004 Madrid train bombings and the execution of search warrants and other court orders in the Mayfield family home and in Mr. Mayfield's law office." A Justice Department statement released Wednesday said Mayfield was not targeted because of his Muslim faith and that the FBI had taken steps to improve its fingerprint identification process "to ensure that what happened to Mr. Mayfield does not happen again." "Mr. Mayfield and his family felt it was in their best interest to get on with their lives," said Mayfield's attorney, Elden Rosenthal. "No amount of money can compensate Mr. Mayfield for being held as a prisoner and being told he faced the death penalty [for the Madrid bombings]." Mayfield said his suit was not about money. "It's about regaining our civil rights, our freedom and most important, our privacy," he said. He and his attorneys said the settlement will allow him to continue the portion of his lawsuit challenging the constitutionality of the Patriot Act. Mayfield contends that his home was searched under provisions of the Patriot Act. ==================================================================== Criminal, Rogue and RACIST elements have penetrated all the branches of USA and world governments. We know that on 911 FBI bastards ran all over in the neighborhood of Pentagon trying to confiscate EVIDENCE of the 911 crime that no Boeing Passenger Airliner hit Pentagon. They have stil not released the evidence. 911 was inside job. FBI is the BEST of the criminal branches ... THERE ARE MORE EVIL AND BIGGER ROGUES IN CIA, NSA, Mossad, PENTAGON AND THE WHITE HOUSE. Dont forget that BASTARD, NIXON and JOHNSON who sank USS LIBERTY and KILLED AMERICANS with the help of ISRAEL ... FBI is the BEST of the criminal branches ... THERE ARE MORE EVIL AND BIGGER ROGUES IN CIA, NSA, PENTAGON AND THE WHITE HOUSE. Dont forget that BASTARD, NIXON and JOHNSON who sank USS LIBERTY and KILLED AMERICANS with the help of ISRAEL ... THE ONLY ONLY REASON FBI DID THIS IS BECAUSE THEIR CRIME WAS UNCONCEALABLE. UNDER THE PRETEXT OF SELF-DEFENSE, MANY OF THESE AGENCY OFFICIALS HAVE COVERED THEIR CRIMES AND DESTROYED EVIDENCE OF THEIR CRIMES. FBI COVERED UP A CHILD PEDOPHILIA RING THAT WAS LINED TO REAGAN AND HERBERT WALKER BUSH. There is a VIDEO on google of the investigation. From emin.shopper at gmail.com Fri Nov 3 14:54:47 2006 From: emin.shopper at gmail.com (emin.shopper at gmail.com) Date: 3 Nov 2006 11:54:47 -0800 Subject: emacs shell hangs on W32 with python References: <1162508249.399337.233170@m73g2000cwd.googlegroups.com> <1162563579.312620.247480@b28g2000cwb.googlegroups.com> <1162567058.729292.316730@h54g2000cwb.googlegroups.com> Message-ID: <1162583687.764788.77440@h54g2000cwb.googlegroups.com> Lennart Borgman wrote: > Could you then please post a bug report? Just choose "Help - Send bug > report" from the menus. I sent a bug-report to the emacs list as requested and got an email reply saying the message is being held for a moderator to look at. Since the bug seems to be in the interaction of emacs with python, I'm also cross-posting this to comp.lang.python in case anyone there can help. (Note this bug shows up in all the versions of emacs that I have tried including Xemacs and GNU Emacs 21). The body of the bug-report is below: I started emacs with -q did ESC-x shell and entered the following ---------------------------------------------------------------------- Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. h:\projects\arcp_db\trunk\src\gui>c:\python25\python.exe -i c:\python25\python.exe -i 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 Tkinter >>> t = Tkinter.Tk() >>> 2 ---------------------------------------------------------------------- Note that after the call to Tkinter.Tk() my python window freezes and no longer works. Killing the Tk window does not help. I realize that this may seem like a bug in python and not emacs except that if I do exactly the same thing through a dos shell I have no problems (i.e., python keeps accepting input). Consequently, it seems like emacs is doing something funky when running the shell that interferes with python in a way that running the shell without emacs would not do. Sincerely, -Emin Martinian In GNU Emacs 23.0.0.1 (i386-mingw-nt5.1.2600) of 2006-10-16 on DTOP X server distributor `Microsoft Corp.', version 5.1.2600 configured using `configure --with-gcc (4.1) --cflags -O2 -g0 -march=i386 -mtune=i686 -pipe -IC:/gnuwin32/include_emacs -IC:/gnuwin32/lib -IC:/gnuwin32/src --ldflags -s ' Important settings: value of $LC_ALL: nil value of $LC_COLLATE: nil value of $LC_CTYPE: nil value of $LC_MESSAGES: nil value of $LC_MONETARY: nil value of $LC_NUMERIC: nil value of $LC_TIME: nil value of $LANG: ENU locale-coding-system: cp1252 default-enable-multibyte-characters: t Major mode: Lisp Interaction Minor modes in effect: encoded-kbd-mode: t tooltip-mode: t tool-bar-mode: t mouse-wheel-mode: t menu-bar-mode: t file-name-shadow-mode: t global-font-lock-mode: t font-lock-mode: t blink-cursor-mode: t global-auto-composition-mode: t auto-composition-mode: t auto-compression-mode: t line-number-mode: t Recent input: Recent messages: (c:\Program Files\emacs-23\ntemacs23\bin\emacs.exe -q) Loading encoded-kb...done For information about the GNU Project and its goals, type C-h C-p. [2 times] Loading emacsbug... Loading regexp-opt...done Loading emacsbug...done From gagsl-py at yahoo.com.ar Sat Nov 18 00:23:40 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 18 Nov 2006 02:23:40 -0300 Subject: How can I speed this function up? In-Reply-To: References: Message-ID: <7.0.1.0.0.20061118014221.01d63440@yahoo.com.ar> At Friday 17/11/2006 23:40, Chris wrote: >This is just some dummy code to mimic what's being done in the real >code. The actual code is python which is used as a scripting language in >a third party app. The data structure returned by the app is more or >less like the "data" list in the code below. The test for "ELEMENT" is >necessary ... it just evaluates to true every time in this test code. In >the real app perhaps 90% of tests will also be true. > >So my question is how can I speed up what's happening inside the >function write_data()? Only allowed to use vanilla python (no psycho or >other libraries outside of a vanilla python install). > >I have a vested interest in showing a colleague that a python app can >yield results in a time comparable to his C-app, which he feels is mch >faster. I'd like to know what I can do within the constraints of the >python language to get the best speed possible. Hope someone can help. If you can assume that all items have 6 numbers, it appears best to unroll the inner iteration. Below is my best attempt with ideas from other replies too, including some alternatives. The timing is only approximate and had a wide dispersion; median of three. But it's clear that the main gain comes from calling out.write only once: Notice that you can't, in general, use i[0] is 'ELEMENT' unless you can guarantee that i[0] is an interned string (and if it comes from another process, chances are it isn't). Using intern(i[0]) is 'ELEMENT' would work, but slows down your program. # initial: 11.66s def write_data1(out, data): write = out.write for i in data: if i[0] == 'ELEMENT': # sorry but can't guarantee identity # 6.21s write("ELEMENT %06d %s\n" % (i[1], "%d %d %d %d %d %d " % i[2])) # 6.92s # write("ELEMENT %06d %s \n" % (i[1], " ".join(map(str,i[2])))) # 8.30s [i] # i2 = i[2] # write("ELEMENT %06d %d %d %d %d %d %d \n" % (i[1], i2[0], i2[1], i2[2], i2[3], i2[4], i2[5])) # 7.04s __getitem__ # i2 = i[2].__getitem__ # write("ELEMENT %06d %d %d %d %d %d %d \n" % (i[1], i2(0), i2(1), i2(2), i2(3), i2(4), i2(5))) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From p.lavarre at ieee.org Fri Nov 10 09:11:24 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 10 Nov 2006 06:11:24 -0800 Subject: announce: FAQs suggested References: <1163166123.773324.126160@m7g2000cwm.googlegroups.com> Message-ID: <1163167884.303515.257820@k70g2000cwa.googlegroups.com> > > > http://effbot.org/pyfaq/suggest.htm > > FAQ: How do I say returns void in ctypes? > That's in the ctypes documentation, where it belongs. Thank you, before I never had found "Use None for void a function not returning anything" at: http://starship.python.net/crew/theller/ctypes/reference.html Now I see, that find corresponds to: http://docs.python.org/dev/lib/ctypes-foreign-functions.html I think this remains an FAQ, because I see void is missing from much more prominent places: http://docs.python.org/dev/lib/node452.html "Fundamental data types" http://docs.python.org/dev/lib/ctypes-return-types.html Finding a way to suggest improving those docs would help more than suggesting an FAQ, I agree. > > > > http://effbot.org/pyfaq/suggest.htm > > FAQ: How do I say unsigned char in ctypes? > That's in the ctypes documentation, where it belongs. Yes and no. The whole FAQ suggested was: FAQ: How do I say unsigned char in ctypes? A: ctypes.c_ubyte ctypes doesn't define c_uchar. This actually is doc'ed, it's just annoying. Per your kind correction above re void, I see we could also say: FAQ: How do I say returns void in ctypes? A: restype = None ctypes doesn't define c_void. This actually is doc'ed obscurely, it's just irregular. From horpner at yahoo.com Tue Nov 7 09:47:29 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 7 Nov 2006 15:47:29 +0100 Subject: Simple Tkinter problem References: <1162910114.482548.157530@f16g2000cwb.googlegroups.com> Message-ID: On 2006-11-07, gmarkowsky at gmail.com wrote: > I'm trying to write a GUI that will put up multiple widgets in > succession. My problem is that each widget also contains the > previous widgets when they pop up. How do I reinitialize the > widget each time so that it doesn't contain earlier ones? Show your code. > Actually, another question I have is, is there a way to set > python so that it will assume any undefined variable is 0 or > ''? That is, I have several statements like "If k > 0 then so > and so" and I would like it to assume k=0 unless I tell it > otherwise. I've just been defining k=0 at the start of the > program but it seems there should be a better way. The best way to do it is to never use undefined names. -- Neil Cerutti If only faces could talk. --Pat Summerall From johnjsal at NOSPAMgmail.com Wed Nov 8 16:36:02 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Nov 2006 16:36:02 -0500 Subject: is this the right way to do subclasses? In-Reply-To: <45524d03$0$32427$c3e8da3@news.astraweb.com> References: <45522074$0$17101$c3e8da3@news.astraweb.com> <45523133$0$14421$c3e8da3@news.astraweb.com> <45524d03$0$32427$c3e8da3@news.astraweb.com> Message-ID: <45524da8$0$32427$c3e8da3@news.astraweb.com> John Salerno wrote: > Peter Otten wrote: > >> Try it: Fighter(...) will implicitly call Character.__init__(...). > > Ok, I'm confused! :) I thought you had to explicity call a base class's > __init__ method? How is it doing this? Wait, I just might be an idiot. Is it not even necessary for me to call Character's __init__ method? Fighter will inherit it automatically and call it when a Fighter object is created, right? If that's the case, then I don't know what I was thinking! I guess I was thinking more along the lines of how in wxPython, when you subclass a Frame, you have to call Frame.__init__, but maybe that's only because you then do your own stuff in a custom __init__ class, which would have otherwise overridden the Frame.__init__. In this case, I need Character.__init__ and nothing else, right? Now your other method is making sense to me too! :) From robert.kern at gmail.com Sat Nov 4 01:35:01 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 04 Nov 2006 00:35:01 -0600 Subject: Python in sci/tech applications In-Reply-To: <1162590264.209704.316800@b28g2000cwb.googlegroups.com> References: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> <1162590264.209704.316800@b28g2000cwb.googlegroups.com> Message-ID: Thomas Nelson wrote: > How hard would it be to have numpy/ scipy part of the python standard > library? scipy will never, ever be part of the standard library. Some subset of numpy may eventually make it into the standard library, but not any time soon. -- 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 michele.simionato at gmail.com Tue Nov 14 03:26:16 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 14 Nov 2006 00:26:16 -0800 Subject: handling many default values In-Reply-To: References: <1163435611.128470.146660@f16g2000cwb.googlegroups.com> Message-ID: <1163492776.381839.261030@e3g2000cwe.googlegroups.com> Gabriel Genellina wrote: > At Monday 13/11/2006 13:33, Michele Simionato wrote: > > >Alan Isaac wrote: > > > Also, as an aside, no one objected to using > > > self.__dict__.update(kwargs) > > > in the __init__ function of the parameter holding class. > > > >It is a common trick, also shown in the Python cookbook, IIRC. If you > >are anal about > >double underscores, you can also use > > > >vars(self).update(kwargs) > > Not good - that relies on vars() returning the actual __dict__. > From : > "The returned dictionary should not be modified: the effects on the > corresponding symbol table are undefined." I believe the issue is with classes, where vars(klass) returns a dictproxy which is read only. In the case of instances (i.e. the OP' case) vars(self) returns the instance dictionary and my suggestion is correct. However you was right to point out this subtility, it is always worth to know. Michele Simionato From piet at cs.uu.nl Fri Nov 24 16:30:46 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 24 Nov 2006 22:30:46 +0100 Subject: How good is CORBA? References: <6559fb300611211036l306e99d6ibd354dcd285b243@mail.gmail.com> <45634A59.5080501@wiggly.org> Message-ID: >>>>> "Chris Mellon" (CM) wrote: >CM> FYI: Ice is available under the GPL, so if by "pay" you mean "pay >CM> money" that's not your only option. You can also get a commercial >CM> license, similiar to Qt. >CM> I like Ice a lot, it's got hardly any of the ramp up time and learning >CM> curve that CORBA does, and it's extremely efficent. If GPL or cash are >CM> acceptable licensing options to you, then I encourage you to use it >CM> before you head to CORBA. OmniORB's author did some benchmarking and it appeared that omniORB was faster than Ice. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From tomas at fancy.org Tue Nov 21 20:47:02 2006 From: tomas at fancy.org (Tom Plunket) Date: Tue, 21 Nov 2006 17:47:02 -0800 Subject: wx.Process.Kill on Win32 Message-ID: <1oa7m2h7k1fn4ifnp2t4u0ds3nnlv5ctp6@4ax.com> Google indicates that wx.Process.Kill hadn't been implemented some time ago in wxPython for Win32. Is that still the case? It's kind of a drag since several sources (including wxPython wiki) strongly advise (by my reading and intended use) using wxProcess over the built-in stuff, but it's not entirely useful if I can't kill long-running processes from an external driver. To tie into my previous question about mocking in Python, I've got a bunch of scripts that do a bunch of things, and there's one 'master' script which can serialize these things (connecting to databases, downloading lots of data, and applying transforms to that data). I realized that the GUI part could essentially just be a command line generator for the serializer script, and trivially launch the other activities as a separate process. I/O works pretty well and I was happy with it all until I tried to implement the 'Cancel' button. Any more info, now several years after those threads I turned up? thx, -tom! From soring at gmail.com Sat Nov 4 00:58:38 2006 From: soring at gmail.com (soring at gmail.com) Date: 3 Nov 2006 21:58:38 -0800 Subject: WSDL? References: <454ba334$0$12110$88260bb3@free.teranews.com> <1162590557.043667.20130@m73g2000cwd.googlegroups.com> <454baf57$0$12123$88260bb3@free.teranews.com> Message-ID: <1162619918.120539.154960@m7g2000cwm.googlegroups.com> WSDL is a way to describe a webservice (using a XML dialect) in terms of: operations (that have input and output messages) and endpoints (the actual URL to access the webservice). When you accessed your other guy's URL, the "XML API description" you got back was the actual WSDL. So it wasnt' that the URL he gave you was the WSDL, but the actual XML. SOAP is another XML dialect: one sends SOAP messages to the enpoints defined in a WSDL to access a webservice. Usually, the messages defined in a WSDL are the same as the SOAP body part. So WSDL is a very strict way to define webservice APIs, and it covers a lot of aspects of webservices (it has extensions for transactions, security, reliable messaging, etc). By contrast, XMLRPC is a much more loose standard to send data around the web in XML format - it doesn't attempt to regulate too many aspects of webservices, so it's easier to understand and use to start with. To answer your first question as well: to use WSDL for in-house communication sounds like a lot of overkill to me - but on the other hand, if you ever plan to externalize that data (say your company decides to publish some internal module X as a webservice), than it's good to use WSDL to start with. This is the theory :-) Before deciding what standard to use, make sure that your programming language/framework supports it well, otherwise it's no fun. Sorin tobiah wrote: > I recently wrote a SOAP client(?) to read what the guy from > the other company called a WSDL, which was just a URL that > served an XML API description. Is that the same as XMLRPC > (I ask because you mention SOAP). > > Thanks, > > Toby > > WakeBdr wrote: > > XMLRPC and SOAP are the two I'm working with right now. > > > > > > tobiah wrote: > >> Is WSDL the right answer for in house communication > >> between programs written in different languages, or > >> is it more for publishing interfaces for use by parties > >> outside your own company? > >> > >> What else is available for sharing complex structures > >> with processes running programs that were written in > >> other languages? > >> > >> Thanks, > >> > >> Toby > >> > >> -- > >> Posted via a free Usenet account from http://www.teranews.com > > > > -- > Posted via a free Usenet account from http://www.teranews.com From fredrik at pythonware.com Sat Nov 18 09:03:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 18 Nov 2006 15:03:30 +0100 Subject: Having trouble converting popen2 to subprocess In-Reply-To: References: Message-ID: Daniel Klein wrote: > Now here is my attempt to use the 'subprocess' module : > > from subprocess import * > p = Popen(r'c:\home\hw.exe', bufsize=-1, stdin=PIPE, stdout=PIPE, > universal_newlines=True) > fin = p.stdin p.stdin is the *other* process' stdin. if you want to read things it prints, read from p.stdout instead. > print fin.readline() > fin.close() From johnjsal at NOSPAMgmail.com Mon Nov 6 16:11:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 06 Nov 2006 16:11:01 -0500 Subject: sqlite error? Message-ID: <454fa4dc$0$6987$c3e8da3@news.astraweb.com> Am I using the ? placeholder wrong in this example? t = ('hi', 'bye') self.connection.execute("INSERT INTO Personal (firstName, lastName) VALUES ?", t) Traceback (most recent call last): File "C:\Python25\myscripts\labdb\dbapp.py", line 93, in OnSaveRecord self.save_to_database(textfield_values) File "C:\Python25\myscripts\labdb\dbapp.py", line 97, in save_to_database self.connection.execute("INSERT INTO Personal (firstName, lastName) VALUES ?", t) sqlite3.OperationalError: near "?": syntax error From horpner at yahoo.com Thu Nov 30 13:33:05 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 30 Nov 2006 19:33:05 +0100 Subject: Automatic increment References: <8094b1b60611301008n36969305p48bec2c8a0e10ec1@mail.gmail.com> Message-ID: On 2006-11-30, Thomas Ploch wrote: > Gheorghe Postelnicu schrieb: >> Hi, >> >> I have a situation of the following type: >> >> for line in lineList: >> for item in line.split() >> myArray[counter, itemCounter] >> itemCounter = itemCounter + 1 >> counter = counter +1 >> >> Is there a way to get rid of the manual incrementation of the 2 counters? >> >> Thanks, > > for counter in xrange(len(lineList)): > for itemCounter in xrange(len(lineList[counter].split())) > myArray[counter, itemCounter] I was going to suggest replacing the whole loop with nothing as the best way of removing the manual counters. -- Neil Cerutti From rNOSPAMon at flownet.com Thu Nov 30 14:58:52 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 30 Nov 2006 11:58:52 -0800 Subject: Is there a reason not to do this? Message-ID: One of the things I find annoying about Python is that when you make a change to a method definition that change is not reflected in existing instances of a class (because you're really defining a new class when you reload a class definition, not actually redefining it). So I came up with this programming style: def defmethod(cls): return lambda (func): type.__setattr__(cls, func.func_name, func) class c1(object): pass @defmethod(c1) def m1(self, x): ... Now if you redefine m1, existing instances of c1 will see the change. My question is: is there a reason not to do this? Does it screw something up behind the scenes? Is it unpythonic? Why isn't this standard operating procedure? rg From python at hope.cz Tue Nov 21 14:15:47 2006 From: python at hope.cz (Lad) Date: 21 Nov 2006 11:15:47 -0800 Subject: How to sort list Message-ID: <1164136547.137154.126740@m73g2000cwd.googlegroups.com> I have a list of emails and I would like to sorted that list by domains E.g. If the list is Emails=['a at hotmail.com','a at yahoo.com','b at hotmail.com','c at yahoo.com',....] after sorting I would like to have Emails=['a at hotmail.com','b at hotmail.com','a at yahoo.com','c at yahoo.com',....] What is the best/easiest way? Thank you for help L. From no-spam at no-spam-no-spam.invalid Fri Nov 3 17:38:42 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 03 Nov 2006 23:38:42 +0100 Subject: numpy help In-Reply-To: References: Message-ID: Chris Smith wrote: > Howdy, > > I'm a college student and for one of we are writing programs to > numerically compute the parameters of antenna arrays. I decided to use > Python to code up my programs. Up to now I haven't had a problem, > however we have a problem set where we are creating a large matrix and > finding it's inverse to solve the problem. To invert the matrix I've > tried using numpy.numarray.linear_algebra.inverse and > numpy.oldnumeric.linear_algebra.inverse which both give me the same > error ( I was hoping they called different routines but I think they > call the same one ). > try scipy.linalg.inv etc. (you are using outdated old NumPy modules with recent array type which sometimes creates type conflicts. robert From bobjohnson11 at gmail.com Fri Nov 3 17:36:39 2006 From: bobjohnson11 at gmail.com (RobJ) Date: 3 Nov 2006 14:36:39 -0800 Subject: PySchool - Online Python Web Framework Workshop. Message-ID: <1162593399.583357.199570@e3g2000cwe.googlegroups.com> Hi! My Name is Rob Johnson and I am a graduate student at The Richard Stockton College of NJ. To make a long story short, I'm working on my Masters project in the MAIT program (Masters of Arts in Instructional Technology). I have written a proposal to put together a free on-line Python web framework workshop. The workshop will be geared to help people new to Python web frameworks. I am asking for the community's assistance to help me get this project off the ground. As part of my project, I am conducting a survey for people who are interested in learning more about python web frameworks. The survey is located at http://killersurvey.com/answer_survey.php?id=479. I have also started a blog about this experience in order to let people know what I'm doing (http://pyschool.blogspot.com/). If you have a few minutes, please take a couple of minutes to take the quick survey. The survey is anonymous and the information will be used for statistics for my project. Also, any constructive feedback or suggestions that you can give me would be gladly appreciated. Thanks Rob J From fredrik at pythonware.com Wed Nov 29 11:32:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Nov 2006 17:32:43 +0100 Subject: trouble writing results to files In-Reply-To: <1164817139.688429.120410@14g2000cws.googlegroups.com> References: <1164812827.653386.323320@80g2000cwy.googlegroups.com> <1164817139.688429.120410@14g2000cws.googlegroups.com> Message-ID: lisa.engblom at gmail.com wrote: > I can try that. Is using range(len(a)) a bad solution in the sense > that its likely to create an unexpected error? Or because there is a > more efficient way to accomplish the same thing? for-in uses an internal index counter to fetch items from the sequence, so for item in seq: function(item) is simply a shorter and more efficient way to write for item in range(len(seq)): function(seq[item]) also see this article: http://online.effbot.org/2006_11_01_archive.htm#for From sxn02 at yahoo.com Tue Nov 7 14:06:01 2006 From: sxn02 at yahoo.com (Sorin Schwimmer) Date: Tue, 7 Nov 2006 11:06:01 -0800 (PST) Subject: But it was yesterday here! Message-ID: <20061107190601.59004.qmail@web56013.mail.re3.yahoo.com> > I bet you have an email.py somewhere in your sources... You won the bet. I owe you one :-) Thanks, Sorin -------------- next part -------------- An HTML attachment was scrubbed... URL: From breakfastea at gmail.com Sat Nov 11 00:35:55 2006 From: breakfastea at gmail.com (Camellia) Date: 10 Nov 2006 21:35:55 -0800 Subject: UnboundLocalError In-Reply-To: References: <1163083074.786927.184170@i42g2000cwa.googlegroups.com> Message-ID: <1163223355.190176.127030@h48g2000cwc.googlegroups.com> Thank you all so much for all the replies:) But sorry I'm so dumb I can't say I really understand, what do I actually do when I define a function with its name "number"? why does a name of a function has something to do with a variable? Oh wait can I do this in Python?: def a(): def b() so the b() will appear to be a local function which is the possible cause of my little own error because the compiler will interpret the number() as a local function but a global one? On Nov 10, 7:32 am, Rob Williscroft wrote: > Terry Reedy wrote innews:mailman.1994.1163100168.11739.python-list at python.orgin > comp.lang.python: > > >> def main(): > >> number = number() > > > Within a function, a given name can be either global or local, but not > > both. > > Here you are expecting the compiler to interpret the first occurance > > of 'number' as local and the second as global. Humans can often > > resolve such ambiguities correctly, but not necessarily always. So > > this is too much to ask of a program and hence it is not allowed.".. asked too much of the programme", sounds like a BOFH excuse to > me ;-). > > Seriously I'd bet (if I were a gambling man) that this is by design, > not either of "too much work for the interpreter" or "nobody's > submitted a patch". > > IOW: Why should the intepreter do more work just so the user > can find new and interesting ways to shoot them selves in the foot. > > Rob. > --http://www.victim-prime.dsl.pipex.com/ From Leo.Kislov at gmail.com Fri Nov 17 03:54:02 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 17 Nov 2006 00:54:02 -0800 Subject: how to print pdf with python on a inkjet printer. References: Message-ID: <1163753642.836452.294300@h54g2000cwb.googlegroups.com> krishnakant Mane wrote: > hello all. > I am developing an ncurses based python application that will require > to create pdf reports for printing. > I am not using py--qt or wx python. > it is a consol based ui application and I need to make a pdf report > and also send it to a lazer or ink jet printer. > is it possible to do so with python? > or is it that I will have to use the wxpython library asuming that > there is a print dialog which can open up the list of printers? > if wx python and gui is the only way then it is ok but I will like to > keep this application on the ncurses side. Assuming you are on a UNIX-like system, you really need to setup CUPS (or may be your system already provides CUPS). PDF seems to be the future intermediate format for UNIX printing and CUPS already supports printing PDF files, just run "lp your_file.pdf" to print a file. CUPS only have command line interface: -- Leo From sjmachin at lexicon.net Wed Nov 22 05:28:04 2006 From: sjmachin at lexicon.net (John Machin) Date: 22 Nov 2006 02:28:04 -0800 Subject: Is there a list comprehension for this? In-Reply-To: References: <1164143944.874745.19470@f16g2000cwb.googlegroups.com> <1164171602.525542.56750@f16g2000cwb.googlegroups.com> Message-ID: <1164191284.251308.316810@f16g2000cwb.googlegroups.com> Steven D'Aprano wrote: > On Tue, 21 Nov 2006 21:00:02 -0800, John Machin wrote: > > > Steven D'Aprano wrote: > > > > [snip] > > > >> def running_sum(dw): > >> """Return a list of the running sums of sequence dw""" > >> rs = [0]*len(dw) > >> for i in range(len(dw)): > >> rs[i] = dw[i] + rs[i-1] > > > > Please explain to the newbies why there is no exception raised when > > rs[i-1] is executed for i == 0, and state whether you consider this is > > a Good Idea or a Filthy Trick or a Fortunate Accident. > > Because rs[0-1] is just rs[-1], which fetches the LAST item of the list. I > cunningly initialised the list to all zeroes, so adding zero to the first > term doesn't change the result value. > > It is a variation of the sentinel technique, where you add an extra value > to the beginning or end of a list so that you don't need to treat the > first or last item differently. In this specific case, I think it is a > combination of Good Idea and Fortunate Accident, but since the > meaning of list[-1] is both deliberate and well-documented, it is > certainly not a Filthy Trick. > Fair enough. But it does make the concerned reader go back a couple of lines to see why it doesn't run amok. Here's my attempt at a no-reader-backtracking solution: def running_sum_2(dw): rs = dw[:1] for i in xrange(1, len(dw)): rs.append(dw[i] + rs[-1]) return rs Comments invited. Cheers, John From john at castleamber.com Thu Nov 16 13:37:41 2006 From: john at castleamber.com (John Bokma) Date: 16 Nov 2006 18:37:41 GMT Subject: Python v PHP: fair comparison? References: <136ED738BD4F1545B97E4AC06FF6370734BFDC@DMSP-MSG-EVS01.mail.pvt> Message-ID: Tim Chase wrote: > Demel, Jeff wrote: >> Walterbyrd wrote: >>> Okay, where can I get Python and Apache 2.X for $10 a year? >> >> Webfaction.com > > Um, I think you're off by an order of magnitude. Walterbyrd > asked about $10/*year* and webfaction.com charges $7.50/*month*. > Well, I suppose if one only needed one and a third months of > hosting during the course of the year, it might do for ya. ;-) > > I can't say I've come across any hosting places that serve up PHP > for $10/yr either...the closest I've found is about $3.50/mo > (which also provides Python CGI). hostingforabuck.com, $12/year and I am sure that Python CGI is no problem at all. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From john106henry at hotmail.com Mon Nov 6 19:23:08 2006 From: john106henry at hotmail.com (John Henry) Date: 6 Nov 2006 16:23:08 -0800 Subject: shutil: permission denied errors on windows In-Reply-To: <31b03$454f63b6$544abc47$26270@news.hispeed.ch> References: <31b03$454f63b6$544abc47$26270@news.hispeed.ch> Message-ID: <1162858987.931532.61530@h48g2000cwc.googlegroups.com> I use the copy function a lot and never have problem. I suggest that you write a no brainer standalone test code and if it still fails there, then you have a problem with your installation. Antoine De Groote wrote: > Google tells quite some things about it, but none of them are satisfactory. > > I'm on Windows, and shutil operations (e.g. move, copy) throw [Errno 13] > Permission denied all the time, for the source files. It seems that this > is the case for all my files. But what I don't understand is that > yesterday it still worked. I didn't change anything on my system though > (at least not that I am aware of). I restarted the computer several > times to see if that helped, but it didn't. Also I can't find a process > that would be using the files... > > Has anybody experienced this problem before, or have a solution? > > Kind regards, > antoine > > Here's the code that throws the errors > > [...] > for l in files: > from_file = os.path.join(dir, l) > to_file = from_file.replace(tree_top, backup_dir) > try: > if not os.path.exists(to_file): > log('Copying new %s' % from_file) > counter_new += 1 > shutil.copy2(from_file, to_file) > elif int(os.path.getmtime(from_file)) > > int(os.path.getmtime(to_file)): > log('Copying modified %s' % from_file) > counter_mod += 1 > shutil.copy2(from_file, to_file) > elif os.path.getsize(from_file) > os.path.getsize(to_file): > log('Sizes differ, but not rest: Copying %s' % > from_file) > counter_special += 1 > shutil.copy2(from_file, to_file) > elif os.path.getsize(from_file) < os.path.getsize(to_file): > log('Orig file smaller than backup file: Copying > %s' % from_file) > counter_special += 1 > shutil.copy2(to_file, backup_dir+'DIFF_SIZE') > shutil.copy2(from_file, to_file) > else: > #log('not treated: %s' % l) > pass > > except (OSError, IOError), e: > not_accessible += 1 > print e > [...] From rrr at ronadam.com Wed Nov 1 17:19:13 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 01 Nov 2006 16:19:13 -0600 Subject: Style for modules with lots of constants In-Reply-To: References: <1162398506.919161.145290@m7g2000cwm.googlegroups.com> Message-ID: Neil Cerutti wrote: > On 2006-11-01, bearophileHUGS at lycos.com wrote: >> Neil Cerutti: >>> scriptref = glk.fileref_create_by_prompt('Transcript+TextMode', >>> 'WriteAppend', 0) >> That "+" sign seems useless. A space looks enough to me. The >> functions can accept case-agnostic strings and ignore spaces >> inside them. Example: >> ('transcript textmode ', 'writeappend', 0) > > That's pretty cool. Not as pretty, but easier for users, > possibly. > >>> Parsing the combinable bitfield contants might be slowish, >>> though. >> I think you have to test if this is true for your situation. >> Management of interned strings is probably fast enough >> (compared to the rest of things done by the Python interpreter) >> for many purposes. > > Agreed. I meant I'd have to later test if it's were fast enough. I've found using plain strings as flags has several advantages. The value 'textmode' is always 'textmode', there is no dependency on a module or class being imported or initialized. It avoids having to type namespace prefixes such as thismod.textmode, or myclass.textmode or importing a bunch of values into global name space. Strings comparisons in python are very fast. The disadvantage is an invalid flag may pass silently unless you do some sort of validation which may slow things down a bit. Ron From rtw at freenet.co.uk Sat Nov 25 19:10:12 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 25 Nov 2006 18:10:12 -0600 Subject: case insensitive dictionary References: <1164494606.514366.124810@l39g2000cwd.googlegroups.com> Message-ID: John Henry wrote in news:1164494606.514366.124810 @l39g2000cwd.googlegroups.com in comp.lang.python: > I believe the standard dictionary should be amened to allow the use of > case insensitive keys - as an option. class idict( dict ): class __istr( str ): def __eq__( self, other ): return self.lower() == other.lower() def __hash__( self ): return self.lower().__hash__() def __setitem__( self, k, v ): dict.__setitem__( self, idict.__istr( k ), v ) d = idict( a = 1, b = 2 ) d['A'] = 3 print d Rob. -- http://www.victim-prime.dsl.pipex.com/ From johnjsal at NOSPAMgmail.com Wed Nov 8 14:33:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Nov 2006 14:33:01 -0500 Subject: is this the right way to do subclasses? In-Reply-To: References: <45522074$0$17101$c3e8da3@news.astraweb.com> Message-ID: <45523133$0$14421$c3e8da3@news.astraweb.com> Peter Otten wrote: > One way to avoid the repetition: > > class Character(object): > def __init__(self, name, strength, dexterity, intelligence): > self.name = name > self.health = 10 > self.strength = strength > self.dexterity = dexterity > self.intelligence = intelligence > self.fix_attributes() > > class Fighter(Character): > def fix_attributes(self): > self.health += 2 > self.strength += 1 > > You may need a no-op implementation of fix_attributes() in the Character > class. > > Peter But how does this take care of the initialization of the stats? I won't be able to use Fighter to create a character without doing everything in Character, right? From bignose+hates-spam at benfinney.id.au Fri Nov 3 03:00:09 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 03 Nov 2006 19:00:09 +1100 Subject: Javascript is turning into Python?! References: <7xwt6dkn50.fsf@ruckus.brouhaha.com> Message-ID: <87u01h2c52.fsf@benfinney.id.au> Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: > I hadn't seen this before. New Javascript 1.7 features: > - Generators > - Iterators > - Array comprehensions > - Destructuring assignment > > Sounds like another language we know. The current developers of Javascript have been quite open during development of 1.7 that they have been inspired by Python for many of the new features. (Tried to find a URL, but my search-fu is weak today.) -- \ "Try to become not a man of success, but try rather to become a | `\ man of value." -- Albert Einstein | _o__) | Ben Finney From Roberto.Bonvallet at cern.ch Thu Nov 30 04:52:35 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Thu, 30 Nov 2006 09:52:35 +0000 (UTC) Subject: for i in range() anti-pattern [was Re: trouble writing results to files] References: <1164812827.653386.323320@80g2000cwy.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Wed, 29 Nov 2006 17:00:30 +0100, Fredrik Lundh wrote: > >> Neil Cerutti wrote: >> >>>> BTW, iterating over range(len(a)) is an anti-pattern in Python. >>> >>> Unless you're modifying elements of a, surely? >> >> and needs to run on a Python version that doesn't support enumerate. > > This isn't meant as an argument against using enumerate in the common > case, but there are circumstances where iterating with an index variable > is the right thing to do. "Anti-pattern" tends to imply that it is always > wrong. Right, I should have said: "iterating over range(len(a)) just to obtain the elements of a is not the pythonic way to do it". Cheers, -- Roberto Bonvallet From fredrik at pythonware.com Sat Nov 11 17:16:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Nov 2006 23:16:23 +0100 Subject: explicit self revisited In-Reply-To: References: Message-ID: Peter Maas wrote: > What do you think? cannot all you clueless trolls who cannot think of a single useful thing to contribute to Python start your own newsgroup? From gagsl-py at yahoo.com.ar Wed Nov 8 14:15:41 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 08 Nov 2006 16:15:41 -0300 Subject: Cactching Stdout In-Reply-To: <1162976981.747479.226680@m7g2000cwm.googlegroups.com> References: <1162976981.747479.226680@m7g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20061108153118.05a81150@yahoo.com.ar> At Wednesday 8/11/2006 06:09, Massi wrote: >Hi everyone! I'm writing a python script which uses a C-written dll. I >call the functions in the dll using ctypes, but I don't know how to >catch the output of the "printf" which the C functions use. In fact I >don't even know if it is possible! I've heard something about PIPE and >popen...is this what I need? How can I use them? It is very important >for me that I could take the output in real-time. Since you are calling a function the same process, popen&co won't help. This is just an idea; printf is writting to STDOUT; you could replace STDOUT with the write end of a pipe, and read from the other end. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From sjmachin at lexicon.net Mon Nov 13 04:52:20 2006 From: sjmachin at lexicon.net (John Machin) Date: 13 Nov 2006 01:52:20 -0800 Subject: Jython compile errors ... In-Reply-To: <1163410573.124074.127560@k70g2000cwa.googlegroups.com> References: <1163406931.241442.243390@e3g2000cwe.googlegroups.com> <1163410573.124074.127560@k70g2000cwa.googlegroups.com> Message-ID: <1163411540.429639.100250@i42g2000cwa.googlegroups.com> Eric_Dexter at msn.com wrote: > If you are looking for an example of jython there is one in embeded in > csound blue. available from the csounds.com website I believe. I have > used it under the new java framework. I am not far enough along to > know if you are missing brackets {} exc and () and one ; but you can > try getting the python part to work under python 2.3 > > > https://sourceforge.net/project/showfiles.php?group_id=156455 > > donkeyboy wrote: > > All, > > > > I've tried the jythonc compiler to try and create an applet to see how > > it works, but I get a number of Java compile errors that are way above > > my knowledge. Does anyone know what any of the following means? I'm > > using JDK 1.5.0_09, under Win XP SP2. > > > > Runnnig the file " jython FILENAME" works, so I don't know what's > > happening. Any thoughts? [snip] I was about to nominate somebody else for the monthly Most Astonishing Result of Misreading a Post award, but the above just blew it away :-) From cemerick at snowtide.com Wed Nov 15 14:33:33 2006 From: cemerick at snowtide.com (Chas Emerick) Date: Wed, 15 Nov 2006 14:33:33 -0500 Subject: lxml/ElementTree and .tail Message-ID: <963FC6E3-F9E2-402E-B8E7-1FB1C8B36295@snowtide.com> I looked around for an ElementTree-specific mailing list, but found none -- my apologies if this is too broad a forum for this question. I've been using the lxml variant of the ElementTree API, which I understand works in much the same way (with some significant additions). In particular, it shares the use of a .tail attribute. I ran headlong into this aspect of the API while doing some DOM manipulations, and it's got me pretty confused. Example: >>> from lxml import etree as ET >>> frag = ET.XML('headinsidetail') >>> b = frag.xpath('//b')[0] >>> b >>> b.text 'inside' >>> b.tail 'tail' >>> frag.remove(b) >>> ET.tostring(frag) 'head' As you can see, the .tail text is removed as part of the element -- but it IS NOT part of the element. I understand the use of the .tail attribute given the desire to simplify the API by avoiding pure text nodes, but it seems entirely inappropriate for the tail text to disappear into the ether when what is technically a sibling node is removed. Performing the same operations with the Java DOM api (crimson, in this case it turns out) yields what I would expect (here I'm using JPype to access a v1.4.2 JVM through python -- which makes things somewhat less painful): >>> from jpype import * >>> startJVM(getDefaultJVMPath()) >>> builder = javax.xml.parsers.DocumentBuilderFactory.newInstance ().newDocumentBuilder() >>> xml = java.io.ByteArrayInputStream(java.lang.String ('headinsidetail').getBytes()) >>> doc = builder.parse(xml) >>> a = doc.documentElement >>> a.toString() u'headinsidetail' >>> b = a.getElementsByTagName('b').item(0) >>> a.removeChild(b) >>> a.toString() u'headtail' (Sorry for the Java comparison, but that's where I first cut my teeth on XML, and that's where my expectations were formed.) That's a pretty significant mismatch in functionality. I certainly understand the motivations of Mr. Lundh to make the ET API as pythonic as possible, but ET's behaviour in this specific context is flatly wrong as far as I can see. I would have expected that a removal operation would have appended 's tail text to the text of (or perhaps to the tail text of 's closest preceding sibling) -- something that I think I'm going to have to do in order to continue using lxml / ElementTree. I ran this issue past a few people I know who've worked with and written about ElementTree, and their response to this apparent divergence between the ET DOM API and "standard" DOM APIs was roughly: "that's just the way it is". Comments, thoughts? Chas Emerick Founder, Snowtide Informatics Systems Enterprise-class PDF content extraction cemerick at snowtide.com http://snowtide.com | +1 413.519.6365 From rrr at ronadam.com Sun Nov 12 01:23:20 2006 From: rrr at ronadam.com (Ron Adam) Date: Sun, 12 Nov 2006 00:23:20 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: <17750.22816.636590.485360@montanaro.dyndns.org> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <17750.22816.636590.485360@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > >>>>> I'm not sure why '\'s are required to do multi-line before the colon. > >>>> Special cases aren't special enough to break the rules. > >>>> > >>>> Georg > >>> A bit of a circular answer. > >>> > >>> Why the rule? -> So not to break the rule? > >> > >> You proposed to allow leaving off line continuation '\' only in the > >> "if", "for" and "while" headers. This is a special case in my eyes. > > Ron> I wasn't that specific and it was related to Michael's suggestion > Ron> the colon wasn't needed. If the need for '\' was dropped in > Ron> multi-line block headers, then the colon would be required for an > Ron> obvious reason. > > But \ is used to continue all sorts of statements/expressions, e.g.: > > x = a + \ > b > > not just conditionals. > > Skip Of course, and your point is? How about if it be ok to continue to use '\' in headers, but it also be ok to not to? That would be the backward compatible way to change it. This doesn't answer the question I was asking, are there any situation where it would cause problems? And if so, that reason would be a good and explicit reason for not making such a change. Ron From Roberto.Bonvallet at cern.ch Thu Nov 30 10:09:43 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Thu, 30 Nov 2006 15:09:43 +0000 (UTC) Subject: PythonTidy References: Message-ID: Chuck Rhode wrote: [...] > Thanks, too, for trying *PythonTidy*. No, thanks you for writing such a tool! > [...] nevertheless, most [options] are declared near the beginning where > they sit just begging for end-user involvement. See: CODING_SPEC and > SHEBANG. The fact that I immediately noticed them and came up with an example to raise both issues is a indicator of how easy it would be to customize the script :) Cheers! -- Roberto Bonvallet From skip at pobox.com Tue Nov 7 15:28:00 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 7 Nov 2006 14:28:00 -0600 Subject: Tired of spam, unrelated email? In-Reply-To: <000601c7029a$7b0a7310$6400a8c0@genesis> References: <000601c7029a$7b0a7310$6400a8c0@genesis> Message-ID: <17744.60496.665376.34698@montanaro.dyndns.org> Tired of spam, unrelated email? You mean, like your message? Skip From bignose+hates-spam at benfinney.id.au Thu Nov 23 20:00:06 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 24 Nov 2006 12:00:06 +1100 Subject: Text markup conventions (was: sys.stderr.write and sys.exit) References: <1164278785.075748.220690@j44g2000cwa.googlegroups.com> Message-ID: <874pspveuh.fsf_-_@benfinney.id.au> Dennis Lee Bieber writes: > Ben Finney wrote: > > (Note: The underscore '_' is a valid character in Python code, so > > I was quite confused by what you wrote and had to read it several > > times to see that you were intending the underscores not to be > > part of the code. Better to show a line of code on its own line in > > your message.) > > Old "rich text" email format effectors... *word* => bolded, /word/ > => italic, _word_ => underscored. Yes, I use those (or similar) myself, but only in natural language where the context makes it clear that the punctuation characters are not intended to be part of the content. When showing program code, it's a poor choice to use punctuation characters for such markup, since it's not clear which ones are part of the code. -- \ "It's a good thing we have gravity or else when birds died | `\ they'd just stay right up there. Hunters would be all | _o__) confused." -- Steven Wright | Ben Finney From tundra at tundraware.com Wed Nov 8 14:48:00 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: Wed, 08 Nov 2006 13:48:00 -0600 Subject: Problem getting a file pathname with tkFileDialog In-Reply-To: <1163012468.055428.124690@h48g2000cwc.googlegroups.com> References: <1163012468.055428.124690@h48g2000cwc.googlegroups.com> Message-ID: cdroulers at hotmail.com wrote: > Hello, > I am working on a school project that requires me to get the path of a > filename for future treatment. > I've tried getting a file with tkFileDialog.askopenfile. > > > ******************************************** > import tkFileDialog > file = tkFileDialog.askopenfile() > print file > ******************************************** > > > It prints the opened files stuff, but I just can not find how to get > that path as a string. I've searched around google and the present > group, and found no documentation on the file class used with > tkFileDialog. Does someone have a solution for that? > > Thank you > > Christian > How about: print file.name -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From anthra.norell at vtxmail.ch Mon Nov 6 04:22:31 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Mon, 06 Nov 2006 10:22:31 +0100 Subject: string to list of numbers conversion In-Reply-To: <1162730071.953080.284980@i42g2000cwa.googlegroups.com> References: <1162730071.953080.284980@i42g2000cwa.googlegroups.com> Message-ID: <454EFED7.6000207@vtxmail.ch> jm.suresh at no.spam.gmail.com wrote: > Hi, > I have a string '((1,2), (3,4))' and I want to convert this into a > python tuple of numbers. But I do not want to use eval() because I do > not want to execute any code in that string and limit it to list of > numbers. > Is there any alternative way? > > Thanks. > Suresh > > s = '((1,2), (3,4))' separators = re.compile ('\(\s*\(|\)\s*,\s*\(|\)\s*\)') tuple ([(float (n[0]), float (n[1])) for n in [pair.split (',') for pair in separators.split (s) if pair]]) ((1.0, 2.0), (3.0, 4.0)) Frederic From bmichel at gmail.com Wed Nov 22 08:31:03 2006 From: bmichel at gmail.com (bmichel at gmail.com) Date: 22 Nov 2006 05:31:03 -0800 Subject: XML Validation in Python using XSV In-Reply-To: <45644E9A.3030209@web.de> References: <1164200431.878328.175100@f16g2000cwb.googlegroups.com> <45644E9A.3030209@web.de> Message-ID: <1164202262.974495.289490@f16g2000cwb.googlegroups.com> No particular reason for XSV I just want to validate XML files against an XML schema through Python. If you can suggest any other package for debian, I'll be glad to try it. Michel Stefan Behnel wrote: > bmichel at gmail.com wrote: > > I'd like to use XSV for validating an XML file in Python. > > I am working on Linux Debian platform. > > I'm not sure how to install XSV and how to configure it. My goal is to > > be able to import the XSV library in Python and be able to use it's > > functions. > > You can use "dpkg" to install the .deb. Read "man dpkg". > > BTW: any reason you need to use XSV? There are some other libraries out there > that can validate XML based on XML Schema and RelaxNG, e.g. lxml. They are > much more powerful than XSV. > > Stefan From no-spam at no-spam-no-spam.invalid Mon Nov 6 06:58:26 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Mon, 06 Nov 2006 12:58:26 +0100 Subject: Erronous "unsupported locale setting" ? Message-ID: Why can the default locale not be set by its true name? but only by '' ? : PythonWin 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32. >>> import locale >>> locale.getlocale() (None, None) >>> locale.setlocale(locale.LC_ALL,"de_DE") Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\locale.py", line 476, in setlocale return _setlocale(category, locale) Error: unsupported locale setting >>> locale.getdefaultlocale() ('de_DE', 'cp1252') >>> locale.setlocale(locale.LC_ALL,locale.getdefaultlocale()) Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\locale.py", line 476, in setlocale return _setlocale(category, locale) Error: unsupported locale setting >>> locale.setlocale(locale.LC_ALL) 'C' >>> locale.setlocale(locale.LC_ALL,'') 'German_Germany.1252' >>> locale.getlocale() ('de_DE', 'cp1252') >>> From fakeaddress at nowhere.org Mon Nov 27 07:35:10 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Mon, 27 Nov 2006 12:35:10 GMT Subject: working with files and directories In-Reply-To: <7IAah.58105$uv5.416763@twister1.libero.it> References: <7IAah.58105$uv5.416763@twister1.libero.it> Message-ID: <2YAah.18835$Sw1.13785@newssvr13.news.prodigy.com> halex2000 wrote: > Hi all, I'm new with Python, and I thought to use it to automatically rename > some files in a directory, but I don't know where should I search the > functions: to get all the files of a directory, to rename the files and so > on. Python programmers are constantly looking at: http://docs.python.org/lib/lib.html In this case, see 14.1.4, 11.1, and 11.10. Happy hacking. -- --Bryan From maxerickson at gmail.com Mon Nov 6 10:35:22 2006 From: maxerickson at gmail.com (Max Erickson) Date: Mon, 6 Nov 2006 15:35:22 +0000 (UTC) Subject: how do I pass values between classes? References: <1162592180.494470.257040@h54g2000cwb.googlegroups.com> <454C9ECF.5020806@websafe.com> <1162796443.570347.91760@e3g2000cwe.googlegroups.com> Message-ID: "kath" wrote: > hi, Larry Bates .... thanks for the reply... > >> You might consider doing it the same way wx passes things around. >> When you instantiate the subclass pass the parent class' instance >> as first argument to __init__ method. > > Yes thats absolutely right.. > >> That way the subclass can >> easily pass values back to the parent by using that pointer. > > Could you please explain me this.. more clearly. I think it is much > close to the solution. > > > Thank you. > regards, sudhir > Somewhere in the child class: self.parent.do_something(something_to_do_it_with) From bobjohnson11 at gmail.com Sat Nov 4 09:43:19 2006 From: bobjohnson11 at gmail.com (RobJ) Date: 4 Nov 2006 06:43:19 -0800 Subject: PySchool - Online Python Web Framework Workshop. References: <1162593399.583357.199570@e3g2000cwe.googlegroups.com> Message-ID: <1162651399.648891.31580@i42g2000cwa.googlegroups.com> Thanks James and Steve for the feedback I have made the appropriate changes and republished the survey at the following URL: http://killersurvey.com/answer_survey.php?id=490 Rob J James Stroud wrote: > RobJ wrote: > > Hi! My Name is Rob Johnson and I am a graduate student at The Richard > > Stockton College of NJ. To make a long story short, I'm working on my > > Masters project in the MAIT program (Masters of Arts in Instructional > > Technology). I have written a proposal to put together a free on-line > > Python web framework workshop. The workshop will be geared to help > > people new to Python web frameworks. I am asking for the community's > > assistance to help me get this project off the ground. As part of my > > project, I am conducting a survey for people who are interested in > > learning more about python web frameworks. The survey is located at > > http://killersurvey.com/answer_survey.php?id=479. I have also started a > > blog about this experience in order to let people know what I'm doing > > (http://pyschool.blogspot.com/). If you have a few minutes, please take > > a couple of minutes to take the quick survey. The survey is anonymous > > and the information will be used for statistics for my project. Also, > > any constructive feedback or suggestions that you can give me would be > > gladly appreciated. > > > > Thanks > > > > Rob J > > > Q9 should be "check all that apply" or otherwise qualified with "primarily". > > Q10 is missing other types of broadband such as what one might find at > school, and also have the option of multiple selections. From kelong_2000 at yahoo.com Wed Nov 8 10:11:34 2006 From: kelong_2000 at yahoo.com (Kenneth Long) Date: Wed, 8 Nov 2006 07:11:34 -0800 (PST) Subject: ANN: wxPython 2.7.2.0 In-Reply-To: <45518E52.4010306@alldunn.com> Message-ID: <20061108151134.73765.qmail@web51113.mail.yahoo.com> Is there a new version of Demo Docs released also? I get this error from Sourceforge after clicking on the link at wxPython page. Could not read file. Go back. /home/ftp/pub/sourceforge//w/wx/wxpython/wxPython2.7-win32-docs-demos-2.7.2.0.exe Nov 08, 2006 07:10 --- Robin Dunn wrote: > Announcing > ---------- > > The 2.7.2.0 release of wxPython is now available for > download at > http://wxpython.org/download.php. This is expected > to be the last > stepping stone in the path to the next stable > release series, > 2.8.x. We're pushing full speed ahead in order to > get 2.8.0 included > with OSX 10.5, and so far we are very close to being > on schedule. This > release has some house-keeping style changes, as > well as some > user-contributed patches and also the usual crop of > bug fixes. Source > and binaries are available for both Python 2.4 and > 2.5 for Windows and > Mac, as well some pacakges for varous 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. > > > Changes in 2.7.2.0 > ------------------ > > Patch [ 1583183 ] Fixes printing/print preview > inconsistencies > > Add events API to wxHtmlWindow (patch #1504493 by > Francesco Montorsi) > > Added wxTB_RIGHT style for right-aligned toolbars > (Igor Korot) > > Added New Zealand NZST and NZDT timezone support to > wx.DateTime. > > wx.Window.GetAdjustedBestSize is deprecated. In > every conceivable > scenario GetEffectiveMinSize is probably what you > want to use instead. > > wx.Image: Gained support for TGA image file format. > > wx.aui: The classes in the wx.aui module have been > renamed to be more > consistent with each other, and make it easier to > recognize in the > docs and etc. that they belong together. > > FrameManager --> AuiManager > FrameManagerEvent --> AuiManagerEvent > PaneInfo --> AuiPaneInfo > FloatingPane --> AuiFloatingPane > DockArt --> AuiDockArt > TabArt --> AuiTabArt > AuiMultiNotebook --> AuiNotebook > AuiNotebookEvent --> AuiNotebookEvent > > wx.lib.customtreectrl: A patch from Frame Niessink > which adds an > additional style (TR_AUTO_CHECK_PARENT) that > (un)checks a parent when > all children are (un)checked. > > wx.animate.AnimationCtrl fixed to display inactive > bitmap at start > (patch 1590192) > > Patch from Dj Gilcrease adding the > FNB_HIDE_ON_SINGLE_TAB style flag > for wx.lib.flatnotebook. > > wx.Window.GetBestFittingSize has been renamed to > GetEffectiveMinSize. > SetBestFittingSize has been renamed to > SetInitialSize, since it is > most often used only to set the initial (and > minimal) size of a > widget. > > The QuickTime backend for wx.media.MediaCtrl on MS > Windows works > again. Just pass > szBackend=wx.media.MEDIABACKEND_QUICKTIME to the > constructor to use it instead of the default > ActiveMovie backend, > (assuming the quicktime DLLs are available on the > system.) > > -- > Robin Dunn > Software Craftsman > http://wxPython.org Java give you jitters? Relax > with wxPython! > > -- > http://mail.python.org/mailman/listinfo/python-list > hello ____________________________________________________________________________________ Sponsored Link Degrees online in as fast as 1 Yr - MBA, Bachelor's, Master's, Associate Click now to apply http://yahoo.degrees.info From rtw at freenet.co.uk Wed Nov 1 15:55:16 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Wed, 01 Nov 2006 14:55:16 -0600 Subject: Where do nested functions live? References: <4548DDFC.9020409@vtxmail.ch> Message-ID: Steve Holden wrote in news:mailman.1615.1162411287.11739.python-list at python.org in comp.lang.python: > Since we have a class that goes out of scope >> when the function returns, and we don't need more than one instance, >> why bother to make an instance? Why not use the class object itself? >> >> def whatever( new_ms ): >> >> class scope ( object ): >> >> def inner(): >> scope.mseconds = new_ms - s * 1000 >> m, scope.seconds = divmod (s, 60) >> h, scope.minutes = divmod (m, 60) >> d, scope.hours = divmod (h, 24) >> scope.weeks, scope.days = divmod (d, 7) >> > That will need to be > > class scope(object): pass > > to avoid syntax errors, I suspect. There doesn't seem to be any reason > why you couldn't use a class instead of an instance. And, of course, > either might give you problems in the case of a recursive inner > function. What problems would it have that a recursive global function that modified a global object, or a recursive method that modified its instance doesn't have ? Rob. -- http://www.victim-prime.dsl.pipex.com/ From __peter__ at web.de Fri Nov 3 04:14:55 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Nov 2006 10:14:55 +0100 Subject: __doc__ in compiled script References: Message-ID: Gabriel Genellina wrote: > I have a script starting with a docstring. After compiling it with > compile(), is there any way I could get the docstring? __doc__ on the > code object doesn't work. The lazy coder's approach: >>> compiler.parse(""" ... 'the docstring' ... print 42 ... """).doc 'the docstring' Peter From sjmachin at lexicon.net Fri Nov 10 15:16:05 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Nov 2006 12:16:05 -0800 Subject: SyntaxError: Invalid Syntax. In-Reply-To: <1163179622.691812.96170@h48g2000cwc.googlegroups.com> References: <1163178099.156160.29280@k70g2000cwa.googlegroups.com> <1163178336.281812.140580@f16g2000cwb.googlegroups.com> <1163178581.231837.18120@h48g2000cwc.googlegroups.com> <1163179622.691812.96170@h48g2000cwc.googlegroups.com> Message-ID: <1163189765.282387.287880@h54g2000cwb.googlegroups.com> ronrsr wrote: > the exact code that is triggering the error message is: > > zc = zsql.connect() Don't give us one line; give us the whole of the imported module plus the calling script (at least up to the place where it gets the error). That way we can see what is really going on, and someone with mysqldb installed could try to reproduce your problem. > > exact error message: SyntaxError: Invalid Syntax Inexact! The message would have been SyntaxError: invalid syntax Please *DON'T* type in what you think you remember you think you saw on the screen; *COPY/PASTE* the traceback and the error message. > > > but any statement that follows the import statement will trigger it. > > bests, > > r-sr- > > > > > Roberto Bonvallet wrote: > > ronrsr wrote: > > > thanks for the speedy answer. what i meant was: > > > > > > Could you please copy and paste the exact code that is triggering the > > error, and the exact error message? > > > > (BTW, in Python you don't need to end your statements with a semi-colon) > > -- From jrpfinch at gmail.com Fri Nov 24 06:31:52 2006 From: jrpfinch at gmail.com (jrpfinch) Date: 24 Nov 2006 03:31:52 -0800 Subject: Simple threading In-Reply-To: References: <1164295697.757788.26710@e3g2000cwe.googlegroups.com> Message-ID: <1164367912.345480.35420@m7g2000cwm.googlegroups.com> Thank you for your help - the application is proceeding well. From aisaac at american.edu Wed Nov 29 11:52:07 2006 From: aisaac at american.edu (Alan Isaac) Date: Wed, 29 Nov 2006 11:52:07 -0500 Subject: How to refer to Python? References: <9e2f512b0611281348q566dd475xd2f18cf7999180a4@mail.gmail.com> Message-ID: On Tue, 28 Nov 2006 16:51:10 -0500, Fredrik Lundh wrote: > http://effbot.org/pyfaq/are-there-any-published-articles-about-python-that-i-can-reference.htm Maybe: Alan Isaac From antroy at gmail.com Wed Nov 22 03:26:49 2006 From: antroy at gmail.com (Ant) Date: 22 Nov 2006 00:26:49 -0800 Subject: re.match -- not greedy? References: Message-ID: <1164184009.099556.205690@m73g2000cwd.googlegroups.com> EXI-Andrews, Jack wrote: > the '*' and '+' don't seem to be greedy.. they will consume less in > order to match a string: > > >>> import re;re.match('(a+)(ab)','aaab').groups() > ('aa', 'ab') > > this is the sort of behaviour i'd expect from > '(a+?)(ab)' > > a+ should greedily consume a's at the expense of the string not matching They are greedy - they consume as much as possible *without* sacrificing the match. You are thinking I think of possessive quantifiers, such as found in Java, which *will* match as much as possible even if doing so causes the match to fail. This would be written: re.match('(a++)(ab)','aaab') Python doesn't support these possessive quantifiers. From gagsl-py at yahoo.com.ar Tue Nov 14 21:10:36 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 14 Nov 2006 23:10:36 -0300 Subject: jython's future In-Reply-To: <12lkpd83jpjol3f@corp.supernews.com> References: <1163425734.640509.99420@m73g2000cwd.googlegroups.com> <1163433118.770742.262140@e3g2000cwe.googlegroups.com> <4rrjenFspqicU2@mid.uni-berlin.de> <4558ACAC.1030001@web.de> <1163440390.3434.45.camel@dot.uniqsys.com> <12lkpd83jpjol3f@corp.supernews.com> Message-ID: <7.0.1.0.0.20061114224426.01ecae80@yahoo.com.ar> At Tuesday 14/11/2006 21:56, Ed Jensen wrote: >??ukasz Langa wrote: > > Java was at 1.2 (and compiling Hello World took over 5 minutes) > >Bullshit. Complete and utter bullshit. That's the plain truth. Python 1.5.2 final release is of 13 April 1999 JDK 1.2.2 came Friday, July 9, 1999 By the time, Oracle8 installer was a Java application, and required *several* minutes just to load and start running. That's an example of java "speed" at that time. We used to call Java "Ya va!", which in spanish means something like "Wait, I'm coming!" :) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From http Sat Nov 4 02:10:24 2006 From: http (Paul Rubin) Date: 03 Nov 2006 23:10:24 -0800 Subject: Javascript is turning into Python?! References: <7xslh1dmgt.fsf_-_@ruckus.brouhaha.com> <1162596267.518634.164170@h54g2000cwb.googlegroups.com> <7xr6wkt6a3.fsf@ruckus.brouhaha.com> Message-ID: <7x7iybadr3.fsf@ruckus.brouhaha.com> Steve Holden writes: > Wouldn't that be > > with f() as x, g() as y: > blah(x, y) Probably. I haven't started using 2.5 yet. From fredrik at pythonware.com Wed Nov 1 15:47:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 01 Nov 2006 21:47:18 +0100 Subject: CSV module, DictReader problem (bug?) In-Reply-To: References: Message-ID: Jeff Blaine wrote: > It's been a year or so since I written Python code, so maybe > I am just doing something really dumb, but... > > Documentation > ============= > > class DictReader(csvfile[,fieldnames=None, > [,restkey=None[, restval=None[, dialect='excel' > [, *args, **kwds]]]]]) > > > Create an object which operates like a regular reader > but maps the information read into a dict whose keys > are given by the optional fieldnames parameter. If the > fieldnames parameter is omitted, the values in the > first row of the csvfile will be used as the fieldnames. > > Code > ==== > > import csv > > r = csv.DictReader('C:\Temp\Book1.csv') > print r.next() > # EOF here's the documentation for the regular reader, from Python 2.5: reader(...) csv_reader = reader(iterable [, dialect='excel'] [optional keyword args]) for row in csv_reader: process(row) The "iterable" argument can be any object that returns a line of input for each iteration, such as a file object or a list. ... so the reader is simply looping over the characters in your filename. try r = csv.DictReader(open('C:\Temp\Book1.csv')) instead. From no-spam at no-spam-no-spam.invalid Fri Nov 3 12:39:13 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 03 Nov 2006 18:39:13 +0100 Subject: Is there a way to define a true global across modules? In-Reply-To: References: <005d01c6ff5e$2b5d95c0$03000080@hendrik> Message-ID: Fredrik Lundh wrote: > Hendrik van Rooyen wrote: > >> I am struggling with this - I want to define a "system-wide" flag for >> use as a >> semaphore. > > http://www.effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm > Or worse style - if you are too lazy to create a extra global variables module (ab)use the __main__ module als "global": import __main__ __main__.mysemphore += 1 -robert From amk at amk.ca Tue Nov 7 10:02:05 2006 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 07 Nov 2006 09:02:05 -0600 Subject: Barry Warsaw giving Python talk at NASA Message-ID: <_O6dnUlIw7lwAs3YnZ2dnUVZ_q-dnZ2d@speakeasy.net> This is at the Goddard campus: --amk From steve at REMOVE.THIS.cybersource.com.au Sun Nov 19 09:02:11 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 20 Nov 2006 01:02:11 +1100 Subject: tempfile.NamedTemporaryFile wont work References: <456049ca$0$4692$426a74cc@news.free.fr> <4sb0cvFurjq2U1@mid.individual.net> Message-ID: On Sun, 19 Nov 2006 13:18:39 +0100, Bjoern Schliessmann wrote: > Imbaud Pierre wrote: > >> tf = tempfile.NamedTemporaryFile() >> tfName = tf.name >> [...] >> print >> sys.stderr, '%s: %s' % (tfName, ['no', >> 'yes'][os.path.exists(tfName)]) >> subprocess.Popen(['strings', tfName]) > > Just out of curiosity: Why did you assign tf.name to tfname? > > Hypothetically, if tf.name changed, tfname wouldn't follow since > strings are immutable. Well, yes, but if tf.name changed, that won't change the file name on disk either: >>> tf = tempfile.NamedTemporaryFile() >>> tf.name '/tmp/tmpYVV1Ij' >>> os.path.exists(tf.name) True >>> oldname = tf.name >>> tf.name = "/tmp/something" >>> os.path.exists(tf.name) False >>> os.path.exists(oldname) True I'm guessing that binding tf.name to tfName is a micro-optimization. In a very tight loop, name lookups can take considerable time, and one optimization can be to reduce the number of lookups: method = something.method while 1: something.method # needs at least two lookups method # needs a single lookup -- Steve. From deets at nospam.web.de Sun Nov 5 10:41:22 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 05 Nov 2006 16:41:22 +0100 Subject: forwarding *arg parameter In-Reply-To: <6pn3h.125$7b6.98@read3.inet.fi> References: <6pn3h.125$7b6.98@read3.inet.fi> Message-ID: <4r6f10Fq3lvfU1@uni-berlin.de> Tuomas schrieb: > >>> def g(*arg): > ... return arg > ... > >>> g('foo', 'bar') > ('foo', 'bar') > >>> # seems reasonable > ... > >>> g(g('foo', 'bar')) > (('foo', 'bar'),) > >>> # not so good, what g should return to get rid of the outer tuple g(*g('foo', 'bar')) * and ** are the symetric - they capture ellipsis arguments, and they make iterables/dicts passed as positional/named arguments. Diez From fredrik at pythonware.com Wed Nov 1 05:58:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 01 Nov 2006 11:58:02 +0100 Subject: Make all files extension lower by a given directory name In-Reply-To: <20061101103519.23154.qmail@web15015.mail.cnb.yahoo.com> References: <20061101103519.23154.qmail@web15015.mail.cnb.yahoo.com> Message-ID: Tiefeng Wu wrote: > I need make all files extension to lower by a given directory. > Here is my solution: > > import os > > def make_all_file_ext_lower(root): > for path, subdirs, files in os.walk(root): > for file in files: > (name, ext) = os.path.splitext(file) the parens around the target variables are not necessary. > fullname = name[:len(name) - 1] + ext.lower() are you sure you want to strip off the last character in the actual filename? should "FOO.BAR" really be turned into "FO.bar" ? name[:len(name) - 1] can be written name[:-1], btw. > os.rename(os.path.join(path, file), os.path.join(path, fullname)) > > I know this code is lame except for the potential bug, and possibly the lack of error handling for the os.rename call, I'm not sure why you think that. From george.sakkis at gmail.com Tue Nov 7 21:42:47 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 7 Nov 2006 18:42:47 -0800 Subject: object data member dumper? References: <4550cddd$0$12104$88260bb3@free.teranews.com> <4550f442$0$20337$426a34cc@news.free.fr> <4550fbfc$0$12098$88260bb3@free.teranews.com> Message-ID: <1162953767.343243.258420@h54g2000cwb.googlegroups.com> tom arnall wrote: > Bruno Desthuilliers wrote: > > > tom arnall a ?crit : > >> does anyone know of a utility to do a recursive dump of object data > >> members? > >> > > > > What are "object data members" ? (hint: in Python, everything is an > > object - even functions and methods). > > > > What is your real use case ? > > something like: > > class A: > def __init__(self, p1): > self.p1 = p1 > > class B: > def __init__(self,p1, p2): > self.a = A(p1) > self.p2 = p2 > self.v1 = '3' > > class C: > def __init__(self): > self.b = B(3,4) > self.p3 = 5 > > class D: > def __init__(self): > self.v2=2 > self.o1 = C() > self.o2 = B(11,12) > > > d = D() > objectDataDumper(d) > > > would produce something like: > > object of class D with: > o1(C)->b(B)->a(A)->p1=3 > o1(C)->b(B)->p2=4 > o1(C)->b(B)->v1=3 > o1(C)->p3=5 > o2(B)->a(A)->p1=11 > o2(B)->p2=12 > o2(B)->v1=3 > v2=2 > > > tom arnall > north spit, ca > usa At first I thought pickle would be what you're looking for, because that's exactly what it does; it dumps arbitrary objects, without choking on recursive references. Only problem is, it's not human readable (even in its ascii form).If you want it to be human readable, you may check the gnosis.xml.pickle module (http://cheeseshop.python.org/pypi/Gnosis_Utils/1.2.1-a). That's the output of gnosis.xml.pickle.XML_Pickler(d).dumps() on your example: I've also written a similar but less verbose xml dumper. The gnosis.xml package provides a bidirectional mapping between objects and xml (objects -> xml and xml->object) and therefore has to be precise; mine simply generates a nice xml dump of the object which isn't necessarily reversible. Here's the output for your example: 3 4 3 5 11 12 3 2 If you find it suits you better, I'll try to make it available somewhere (probably in the cookbook). George From mensanator at aol.com Wed Nov 22 19:10:49 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 22 Nov 2006 16:10:49 -0800 Subject: Abelson and Python In-Reply-To: <1164239517.067445.179320@e3g2000cwe.googlegroups.com> References: <1164239517.067445.179320@e3g2000cwe.googlegroups.com> Message-ID: <1164240649.628193.65300@f16g2000cwb.googlegroups.com> bearophileHUGS at lycos.com wrote: > While studying the SICP video lectures I have to twist my mind some to > completely understand the lessons. I implement the programs shown there > in both Python and Scheme, and I find the Python implementations > simpler to write (but it's not a fair comparison because I know very > little Scheme still). > > Now some things are changing: > http://lambda-the-ultimate.org/node/1840 > > >The MIT is going to change its curriculum structure that was famous for teaching Scheme in introductory courses. One force behind the reform is no one else than Harold Abelson, famous for his marvelous Scheme opus SICP.< > >The first four weeks of C1 will be a lot like the first four weeks of 6.001, Abelson said. The difference is that programming will be done in Python and not Scheme.< > > > Someone is translating the SIPC programs in Python too: > http://www.codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages#Python > > With slides and code from lectures: > http://courses.csail.mit.edu/6.01/ > http://courses.csail.mit.edu/6.01/fall06/calendar.html > > I like Scheme a bit too, but I consider this is a small victory for > Python :-) No surprise to anyone who's ever tried to use MIT Scheme. > > Bye, > bearophile From xi at gamma.dn.ua Sat Nov 18 16:37:43 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Sat, 18 Nov 2006 23:37:43 +0200 Subject: [Zopyrus] A python IDE for teaching that supports cyrillic i/o In-Reply-To: <200611190249.43660.glebus@asd.iao.ru> References: <20061118190104.GA29614@58sirius016.dc.ukrtel.net> <200611190249.43660.glebus@asd.iao.ru> Message-ID: <20061118213743.GA15906@58sirius016.dc.ukrtel.net> On Sun, Nov 19, 2006 at 02:49:43AM +0600, Gleb Kulikov wrote: > ? ????????? ?? ??????????? 19 ?????? 2006 01:01 Kirill Simonov ???????: > > > first programming language to high school students? It is necessary > > > Unfortunately, most IDEs I tried failed miserably in this respect. My > > > For the record, I've checked IDLE, PythonWin, Eric, DrPython, SPE, and > > Pardon, eric (eric-3.9.0-alt1 is in use), "speak" Russian quite well. > We are trying to teach schoolers with a Python in an advanced elementary > school (9th - 11th). Yes, there is a problem with Cyrillic in eric's built-in > interpreter window (KOI8 locale is used) and *only* in the built-in > interpreter window, but there is short workaround for it: if avoid "# -*- > coding..." declaration, Cyrillic is painted well. Hmm... Perhaps, you are right. I remember quite well seeing UnicodeDecodeError in eric, but now I couldn't reproduce it. Still it would be good if eric could automatically add the BOM mark to files containing non-ASCII characters (for UTF-8). That way the deprecation warning about PEP 263 would be avoided. There is a bigger problem though: it is difficult (if possible) to install it under Windows. Thanks, Kirill From gagsl-py at yahoo.com.ar Wed Nov 8 16:04:58 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 08 Nov 2006 18:04:58 -0300 Subject: Strange re problem on OSX but Not Linux In-Reply-To: <1163008904.817018.186000@h54g2000cwb.googlegroups.com> References: <1163008904.817018.186000@h54g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061108175432.05a4b260@yahoo.com.ar> At Wednesday 8/11/2006 15:01, Brian wrote: >I have a very small script: > >import re > >text = open('eq.txt','r').read() >regex = '[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]' >pattern = re.compile(regex) >match = pattern.findall(text) > >print ''.join(match) > >------------------------------------------------------------------------------- >Here is the error outside of Komodo: > >Traceback (most recent call last): > File "reg1.py", line 1, in > import re > File >"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", >line 5, in > # >AttributeError: 'module' object has no attribute 'compile' >------------------------------------------------------------------------------ > >This is running 2.5 on my OSX box. If I run it (again with 2.5) on my >SUSE machine, I get no errors. > >I am sure that I have overlooked something trivial here - so please be >gentle if it is on the stupid side of things. Dont use regex as a name. Also, do you have any script called "re.py" hidding that library module? or regex.py? -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From nick at craig-wood.com Thu Nov 2 08:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 02 Nov 2006 07:30:03 -0600 Subject: __div__ not recognized automatically References: Message-ID: Anton81 wrote: > class NumX: > ... > def __add__(self,other): > ... > def __div__(self,other): > if not isinstance(other,NumX): other=NumX(other) > ... > > Somewhere else I use > > a=(b+c)/2 > > where all variables are of NumX Type. When I execute the program it > complains that it can't find an operator "/" for "instance" and "integer". > However if I use pdb the same command works when started on the prompt. Also > the manual execution > > a=(b+c).__div__(2) > > works. Any suggestions what goes wrong? Post some code which actually demonstrates the problem. Eg, change this code until it does demonstrate the problem ------------------------------------------------------------ class NumX(object): def __init__(self, value): self.value = long(value) def __add__(self,other): if not isinstance(other,NumX): other=NumX(other) return NumX(self.value + other.value) def __div__(self,other): if not isinstance(other,NumX): other=NumX(other) return NumX(self.value / other.value) def __str__(self): return "%s(%s)" % (self.__class__.__name__, self.value) a = NumX(4) b = NumX(2) print a,b print a+b print (a+b)/2 ------------------------------------------------------------ This prints ------------------------------------------------------------ NumX(4) NumX(2) NumX(6) NumX(3) ------------------------------------------------------------ -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tjreedy at udel.edu Wed Nov 29 23:47:25 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 29 Nov 2006 23:47:25 -0500 Subject: Why are slice indices the way they are in python? References: <1164860915.349821.309920@14g2000cws.googlegroups.com> Message-ID: "Steve Bergman" wrote in message news:1164860915.349821.309920 at 14g2000cws.googlegroups.com... >A couple of off the wall questions. > > It seems to me that there is usually a solid *reason* for things in > Python and I'm wondering about the rationale for the way slicing works Yes, see below. > my_string[2:5] > > gets you the 3rd through the 3rd through the 5th character of the > string because indexing starts at 0 and you get everything up to, but > not including the second index. > > Why? len(s[2:5])== 5-2 s[2:5] + s[5:7] == s[2:7] > Another thing that I've been puzzling over is the pow() function. > > pow(x,y) gives x**y. Fine. > > But pow(x,y,z) gives (x**y) % c you obvious meant (x**y) % z > > I'm curious to know what the pressing reason for such a feature was. Such exponential remainders are used in cryptography work, for instance, with fairly large values, and can be efficiently computed, especially in C, *without* computing a humongous x**y intermediate value. Since this is an int function, it does not really belong in the floating point math module. Terry Jan Reedy From tjreedy at udel.edu Sun Nov 5 15:01:16 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 5 Nov 2006 15:01:16 -0500 Subject: Awesome Python Information References: <1162753631.297470.315570@m7g2000cwm.googlegroups.com> Message-ID: "Brandon" wrote in message news:1162753631.297470.315570 at m7g2000cwm.googlegroups.com... > Check out: www.ChezBrandon.com for awesome megalomania having nothing to do with Python. From bearophileHUGS at lycos.com Wed Nov 22 18:51:57 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Nov 2006 15:51:57 -0800 Subject: Abelson and Python Message-ID: <1164239517.067445.179320@e3g2000cwe.googlegroups.com> While studying the SICP video lectures I have to twist my mind some to completely understand the lessons. I implement the programs shown there in both Python and Scheme, and I find the Python implementations simpler to write (but it's not a fair comparison because I know very little Scheme still). Now some things are changing: http://lambda-the-ultimate.org/node/1840 >The MIT is going to change its curriculum structure that was famous for teaching Scheme in introductory courses. One force behind the reform is no one else than Harold Abelson, famous for his marvelous Scheme opus SICP.< >The first four weeks of C1 will be a lot like the first four weeks of 6.001, Abelson said. The difference is that programming will be done in Python and not Scheme.< Someone is translating the SIPC programs in Python too: http://www.codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages#Python With slides and code from lectures: http://courses.csail.mit.edu/6.01/ http://courses.csail.mit.edu/6.01/fall06/calendar.html I like Scheme a bit too, but I consider this is a small victory for Python :-) Bye, bearophile From Jeff.Demel at JavelinDirect.com Tue Nov 21 16:44:18 2006 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Tue, 21 Nov 2006 15:44:18 -0600 Subject: Psycopg2 | collapse row to string Message-ID: <136ED738BD4F1545B97E4AC06FF6370734C001@DMSP-MSG-EVS01.mail.pvt> resultfile.write(delimiter.join([str(elt) for elt in row])) Worked like a charm. Thanks, Skip. -Jeff -----Original Message----- From: skip at pobox.com [mailto:skip at pobox.com] Sent: Tuesday, November 21, 2006 3:19 PM To: Demel, Jeff Cc: python-list at python.org Subject: Re: Psycopg2 | collapse row to string Jeff> Is there an easy want to create a delimited string from this, for Jeff> example: Jeff> for row in rows: Jeff> if checksomething == 100: Jeff> newline = row[].combine("delimiter of some kind") Jeff> resultfile.write(newline) By "delimited string" do you mean something that can handle fields in which your delimiter appears? If so, you should look at the csv.writer class. If you're absolutely certain your delimiter won't occur in your output, you can just stringify the values and join them: delimiter = "," for row in rows: if checksomething == 100: resultfile.write(delimiter.join([str(elt) for elt in row])) If you know all your row values are already strings it's even easier: delimiter = "," for row in rows: if checksomething == 100: resultfile.write(delimiter.join(row)) Skip This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From xi at gamma.dn.ua Sat Nov 18 14:54:39 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Sat, 18 Nov 2006 21:54:39 +0200 Subject: [Zopyrus] A python IDE for teaching that supports cyrillic i/o In-Reply-To: <455F5D11.8030104@t0mb.net> References: <20061118190104.GA29614@58sirius016.dc.ukrtel.net> <20061118190822.GB19739@phd.pp.ru> <455F5D11.8030104@t0mb.net> Message-ID: <20061118195439.GA3393@58sirius016.dc.ukrtel.net> On Sat, Nov 18, 2006 at 07:20:49PM +0000, tom wrote: > Oleg Broytmann wrote: > > On Sat, Nov 18, 2006 at 09:01:04PM +0200, Kirill Simonov wrote: > > > >> Could anyone suggest me a simple IDE suitable for teaching Python as a > >> first programming language to high school students > >> > which operating system would this concern? IDLE which you might find MS Windows is a must, but having Linux support would be nice too. Unfortunately, IDLE does not work well with non-ASCII input/output. > I personally use pida (http://pida.berlios.de). It is perhaps not a Thanks for the suggestion, I'll check it. Thanks, Kirill From sjmachin at lexicon.net Thu Nov 2 15:55:10 2006 From: sjmachin at lexicon.net (John Machin) Date: 2 Nov 2006 12:55:10 -0800 Subject: Converting a .dbf file to a CSV file References: Message-ID: <1162500910.631386.221620@h54g2000cwb.googlegroups.com> Johanna Pfalz wrote: > Is there a module/method in python to convert a file from .DBF format to > .CSV format? > > Hi Johanna, the best start at the moment is the Python Cookbook recipe that others have quoted. Steps: (1) Input: as per recipe. Note that the recipe handles only the earliest simplest form of dbf files; you may have data types other than C, N, D and L. Note that there are myriads of third-party dbf writing codes out there, and some of them are a little idiosyncratic. I am in the pre-alpha stage of producing a module whose intent is to read just about everything it is given, with lots of assertions, error checks, and warnings. This includes M (memo) fields which are stored in a separate file in 1 of at least 3 formats. If your file causes the recipe to crashes or produce incorrect results, there is a good chance that I may be able to help you. (2) [optional] derive output file headings from names of fields. (3) Convert data values to str, if str(input_value) is not appropriate (4) Write values to csv file. For this I strongly suggest that you use the Python csv module, rather than attempting to reinvent the wheel (and the often-forgotten axle). If, as I guess from your name, that you want the delimiter to be ";" instead of ",", then that can be handled easily with ..., delimiter=";" in the call to csv.writer. HTH, John From ratchetgrid at googlemail.com Sat Nov 25 18:34:11 2006 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Sat, 25 Nov 2006 23:34:11 +0000 Subject: Graph Data Structures In-Reply-To: <1164495892.406863.10090@m7g2000cwm.googlegroups.com> References: <1164465588.399198.173830@f16g2000cwb.googlegroups.com> <1164483939.464327.143450@f16g2000cwb.googlegroups.com> <1164495892.406863.10090@m7g2000cwm.googlegroups.com> Message-ID: <676224240611251534s6fc57ddfje9b0ab3fc838861a@mail.gmail.com> Hi, The idea is that I m going to use it to build graphs for sequence alignment (at the moment), I read a discussion on the corebio (reimplementation of biopython) group about using intervals to represent sequence slices. The idea being that, my graph may contain millions of alignments and storing the sequence (the actual ATGC) is not required. class Node(object): pass class Interval(Node): _id = "gene1" _start = 50 _end = 200 _strand = 1 class Sequence(object): _sequence = "atgtcgtgagagagagttgtgag................." So one interval on one sequence would align to another interval from another sequence, but I want changes I make to the interval to be reflected in the representation later. If I reverse complement it i want the interval to store this information but the Sequence only shows this later on when I call use it calling repr or str. Do you get what I mean. Many Thanks Nathan From steve at holdenweb.com Wed Nov 8 08:16:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Nov 2006 07:16:32 -0600 Subject: MODULE mx.DateTime In-Reply-To: <20061108103133.46775.qmail@web58104.mail.re3.yahoo.com> References: <20061108103133.46775.qmail@web58104.mail.re3.yahoo.com> Message-ID: Antonios Katsikadamos wrote: > Hi all. I am using python2.4 on suse linux 10.1 and i want to import the > mx.DateTime module. does anyone know where i can find this module and > how i can install it on linux? > > I would appreciate any help. > Look on www.egenix.com regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From cfbolz at gmx.de Wed Nov 8 10:03:53 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 08 Nov 2006 16:03:53 +0100 Subject: Summer of PyPy Call for Proposals Message-ID: Last chance to join the Summer of PyPy! ======================================= Hopefully by now you have heard of the "Summer of PyPy", our program for funding the expenses of attending a sprint for students. If not, you've just read the essence of the idea :-) However, the PyPy EU funding period is drawing to an end and there is now only one sprint left where we can sponsor the travel costs of interested students within our program. This sprint will probably take place in Leysin, Switzerland from 8th-14th of January 2007. So, as explained in more detail at: http://codespeak.net/pypy/dist/pypy/doc/summer-of-pypy.html we would encourage any interested students to submit a proposal in the next month or so. If you're stuck for ideas, you can find some at http://codespeak.net/pypy/dist/pypy/doc/project-ideas.html but please do not feel limited in any way by this list! Cheers, Carl Friedrich Bolz and the PyPy team From elderic at ish.de Thu Nov 2 11:18:22 2006 From: elderic at ish.de (elderic) Date: 2 Nov 2006 08:18:22 -0800 Subject: other ways to check for ? References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> <1162477269.980535.202320@h48g2000cwc.googlegroups.com> <1162478431.624590.29290@m7g2000cwm.googlegroups.com> Message-ID: <1162484302.234145.245320@e3g2000cwe.googlegroups.com> > > I just wanted to know if there was a keyword for functions, too. > > > > Then u could've done: type(f) is function > > quite similar to: type(x) is int > > but why do you think you need that, when you have callable() ? unless > you're doing specialized stuff, there's really no reason to distinguish > between function objects and other callables. > > I never said that I need anything - I merely asked for alternatives. =) I'm pretty happy with the types-module or the callable() test. Basically it's just for wrapping the creation of Tk-Buttons, etc. They need a callback and in my process to learn I wanted to know about the possible options to test for that. peace of mind. =) elderic From steve at holdenweb.com Thu Nov 2 10:39:09 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Nov 2006 15:39:09 +0000 Subject: string formatter for tuple In-Reply-To: <1162481557.791817.41690@b28g2000cwb.googlegroups.com> References: <1162481557.791817.41690@b28g2000cwb.googlegroups.com> Message-ID: jeremito wrote: > I have the following in my code > > a = (1,2,3) > print "a = %s" %a > > But when I run this, I get: > > TypeError: not all arguments converted during string formatting > > Now I realize why this happens, a is actually 3 elements when the print > statement is only expecting to print one value. I tried > > print "a = %s" %(a) > > but I got the same error. > > How can I print a tuple with a single string format? > Thanks, > Jeremy > Try print "a = %s" % (a, ) The exception to the "a single object can be formatted as a single argument rather than a tuple" rule is when that single object is itself a tuple! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From dakman at gmail.com Mon Nov 13 13:18:47 2006 From: dakman at gmail.com (dakman at gmail.com) Date: 13 Nov 2006 10:18:47 -0800 Subject: tab compleation input In-Reply-To: <1163434288.421441.48320@f16g2000cwb.googlegroups.com> References: <1163434288.421441.48320@f16g2000cwb.googlegroups.com> Message-ID: <1163441927.046482.218330@e3g2000cwe.googlegroups.com> On a gui on this would be a little bit easier but it's a completley diffrent realm when doing it in the console. It makes it a little more difficult when using stdin.readline() because you can only read line by line. Here is my implmentation. import sys validanswers = [ 'yes', 'no', 'maybe', 'tuesday', 'never' ] while True: sys.stdout.write("Answer the Question: ") answer = sys.stdin.readline().rstrip() for valid in validanswers: if valid.startswith(answer.strip("\t")): answer = valid else: print "Invalid Answer: Please enter a valid answer" continue break print "You have answered, ", answer I'm at school and wasn't able to test it, but it looks like it should work. Eli Criffield wrote: > Here is what i want to do. I have a question in my program, and i want > to do tab completion for the valid answers. > > Say i have : > --snip-- > validanswers = [ 'yes', 'no', 'maybe', 'tuesday', 'never' ] > > #and i ask > > sys.stdout.write("Answer the Question: ") > answer = sys.stdin.readline().rstrip() > if answer not in valid answers: > print "Wrong!" > --snip-- > > But what i want is when i enter the answer i can hit tab and it'll > complete one of the validanswers > I know i can do tab complete with readline and 'raw_input('> ')' but > that's only to execute python commands right? > > Eli From no at spam.com Thu Nov 9 12:32:17 2006 From: no at spam.com (Farshid Lashkari) Date: Thu, 09 Nov 2006 09:32:17 -0800 Subject: Multithreaded C API Python questions In-Reply-To: References: Message-ID: Svein Seldal wrote: > I'm unable to get access to python as long as another python call is > executing. The PyEval_AcquireThread() call blocks until the first call > returns. I was hoping that the python system itself would release the > GIL after some execution, but it itsnt. > > I am dependent upon the ability to have to threads executing in python > land at the same time. How can this be done? Are you creating your threads through python or through C code? If you are only creating it through C code, then make sure you initialize the GIL with the following call at the beginning of your application: PyEval_InitThreads() From my experience, calling PyGILState_Ensure() was enough. I didn't need to call any extra threading functions. But make sure that every call to PyGILState_Ensure() is matched with a call to PyGILState_Release() -Farshid From gagsl-py at yahoo.com.ar Thu Nov 2 15:38:35 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 02 Nov 2006 17:38:35 -0300 Subject: __doc__ in compiled script Message-ID: <7.0.1.0.0.20061102172803.05831948@softlab.com.ar> Hello I have a script starting with a docstring. After compiling it with compile(), is there any way I could get the docstring? __doc__ on the code object doesn't work. I can't use __import__ because the script has top-level statements that have to be executed only once (it's not supposed to be used as a module). --- begin test.py --- body = """ "This is a docstring" x=0 some(code).toBeExecuted("later") """ co = compile(body,'','exec') print co.__doc__ # what can I use for "something" below: ? assert something(co)=="This is a docstring" --- end test.py --- -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From gagsl-py at yahoo.com.ar Tue Nov 7 15:22:25 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 07 Nov 2006 17:22:25 -0300 Subject: Character encoding In-Reply-To: <1162930201.211625.77050@m73g2000cwd.googlegroups.com> References: <1162928072.047884.163420@i42g2000cwa.googlegroups.com> <1162928387.620610.31290@h48g2000cwc.googlegroups.com> <1162930201.211625.77050@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20061107172202.0554d618@yahoo.com.ar> At Tuesday 7/11/2006 17:10, mp wrote: >I'd prefer a more generalized solution which takes care of all possible >ampersand characters. I assume that there is code already written which >does this. Try the htmlentitydefs module -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From cameron.walsh at gmail.com Wed Nov 29 03:03:38 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Wed, 29 Nov 2006 16:03:38 +0800 Subject: PIL throws exception when reading bitmap/pnm data Message-ID: Hi all, I'm trying to extract the data from a bitmap or .pnm file using the following code: import Image img = Image.open("test.bmp","r") data=img.getdata() Unfortunately I get the following exception on Linux, but not on Windows: >>> data=img.getdata() Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.5/site-packages/PIL/Image.py", line 796, in getdata self.load() File "/usr/local/lib/python2.5/site-packages/PIL/ImageFile.py", line 147, in load self.map = mmap.mmap(file.fileno(), size) EnvironmentError: [Errno 19] No such device At this time, I cannot provide the full bitmap for copyright reasons, but I can provide some information about the bitmap: cameron at cameron-laptop:~$ file test.bmp test.bmp: PC bitmap data, Windows 3.x format, 1000 x 1000 x 8 The same code works for .ppm images in the same folder: cameron at cameron-laptop:~$ convert test.bmp test.ppm cameron at cameron-laptop:~$ python import Image img=Image.open("test.ppm") data=img.getdata() But does not work for .pnm images in the same folder: cameron at cameron-laptop:~$ convert test.bmp test.pnm cameron at cameron-laptop:~$ python import Image img=Image.open("test.pnm") data=img.getdata() Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.5/site-packages/PIL/Image.py", line 796, in getdata self.load() File "/usr/local/lib/python2.5/site-packages/PIL/ImageFile.py", line 147, in load self.map = mmap.mmap(file.fileno(), size) EnvironmentError: [Errno 19] No such device PIL Version on Linux and Windows: $Id: Image.py 2337 2005-03-25 07:50:30Z fredrik $ How can I avoid this error without converting each image into a different format? Thanks and regards, Cameron. From amitsoni.1984 at gmail.com Tue Nov 7 07:09:02 2006 From: amitsoni.1984 at gmail.com (amitsoni.1984 at gmail.com) Date: 7 Nov 2006 04:09:02 -0800 Subject: using split function In-Reply-To: References: <1162874036.351559.263280@i42g2000cwa.googlegroups.com> <1162874295.593635.273260@i42g2000cwa.googlegroups.com> Message-ID: <1162901342.522694.37470@b28g2000cwb.googlegroups.com> Thanks a lot, I am done with that part. But now I am facing another problem. I am using the code given below where A is a matrix and row is a sequence. But it gives following error: -------- error------ A[a,:]=row ValueError: setting an array element with a sequence. --------------code---------------- #!/usr/bin/python import numpy file1 = open('matrix.txt', 'r') count = 0 a=0 b=0 c=0 d=0 e=0 A = numpy.zeros([4,4]) while 1: lineStr = file1.readline() if not(lineStr): break count = count + 1 row=lineStr.split() if count<=4: A[a,:]=row a=a+1 elif count<=8: B[b,:]=row b=b+1 elif count<=12: C[c,:]=row c=c+1 elif count<=16: D[d,:]=row d=d+1 elif count<=20: E[e,:]=row e=e+1 file1.close() ---------end of code------------- is there any way to change a sequence to array? thank you Amit Gabriel Genellina wrote: > > > I have to write a code in python to read a matrix from a text file and > > > for that i am using following code. But it gives an error saying > > > "NameError: name 'split' is not defined". Can anyone help me with this. > > A few hints: > - don't use "file" as a name - it shadows the builtin "file" type > - matrix.close() won't work, perhaps you meant file.close()? > > > > ----------------------------------------------------- > > > Also, i want to initialize the matrix A by zeros, but using A=zeros([4, > > > 4]) was giving a similar error "NameError: name 'zeros' is not > > > defined". > > Oh, so *that's* why you build it using standard_normal and then > overwrite the contents! > > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! > ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From robert.kern at gmail.com Tue Nov 21 20:31:47 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 21 Nov 2006 19:31:47 -0600 Subject: Trying to understand Python objects In-Reply-To: <87fyccwacn.fsf@benfinney.id.au> References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> <87fyccwacn.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Or, the attributes are added to a specific instance (often in the > initialisation method) so that each instance has a separate attribute > with the same name:: > > class Point(object): > spam = 4 > def __init__(self): > eggs = 2 There's a typo there. For the sake of not confusing the OP, this is correct: class Point(object): spam = 4 def __init__(self): self.eggs = 2 -- 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 stephen.ayotte at gmail.com Mon Nov 20 10:33:49 2006 From: stephen.ayotte at gmail.com (stephen.ayotte at gmail.com) Date: 20 Nov 2006 07:33:49 -0800 Subject: os x make install dies when compiling zipfile.py on 2.5 and 2.4.4 In-Reply-To: <1164033984.637054.21800@h48g2000cwc.googlegroups.com> References: <1162848039.627681.22980@m7g2000cwm.googlegroups.com> <1164033984.637054.21800@h48g2000cwc.googlegroups.com> Message-ID: <1164036829.496489.227360@h48g2000cwc.googlegroups.com> Sorry about the top-post earlier. I just tested installing 2.4.4 on the same machine that built it--- it ran without a complaint. The line that follows the "Compiling zipfile.py" line (possibly the one that is failing for us) is as follows: Compiling /Home/admin/sayotte/python-test/lib/python2.4/zipfile.py ... PYTHONPATH=/Home/admin/sayotte/python-test/lib/python2.4 \ ./python -Wi -t /Home/admin/sayotte/python-test/lib/python2.4/compileall.py \ -d /Home/admin/sayotte/python-test/lib/python2.4/site-packages -f \ -x badsyntax /Home/admin/sayotte/python-test/lib/python2.4/site-packages Listing /Home/admin/sayotte/python-test/lib/python2.4/site-packages ... Were you by chance also executing the build and install steps on different platforms? From sjmachin at lexicon.net Wed Nov 1 13:39:12 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Nov 2006 05:39:12 +1100 Subject: report progress from C function In-Reply-To: <20061101135354.39489.qmail@web88312.mail.re4.yahoo.com> References: <20061101135354.39489.qmail@web88312.mail.re4.yahoo.com> Message-ID: <4548E9D0.1040007@lexicon.net> On 2/11/2006 12:53 AM, Michael S wrote: > I downloaded Pyrex and ran it through their own > example. The code looks quite messy, and I even saw a > few "goto"s. > I think I will stick with my own code for now. > Thanks in any case. If your own code is doing the right amount of reference counting, error handling and clean-up on module exit, it will look messy and have gotos as well. The advantage of Pyrex is that you write in a high-level language, and it writes the mess. HTH, John From p.m.deandraderodrigues at gmail.com Wed Nov 8 08:31:22 2006 From: p.m.deandraderodrigues at gmail.com (Pedro Rodrigues) Date: Wed, 8 Nov 2006 14:31:22 +0100 Subject: Help solving Python 2.5 crash: The instruction "0x7c168f1d" referenced memory at "0x00000001c" ... Message-ID: <26195e840611080531w5c50e0f3l2fd2c2785877ec34@mail.gmail.com> Hi everyone, recently, I have installed Python 2.5 in a Windows XP (SP2) system, along with the numarray, PIL, and PyWin packages. Since then, I've been getting the following error message whenever I run one of my simulations within PyWin: The instruction "0x7c168f1d" referenced memory at "0x00000001c". The memory could not be "read". If I run the same simulation from the python interactive shell, it still crashes but with a different error message: This application has requested runtime to terminate it in an unusual way. Please contact the application's support team for more information. The simulation demands a lot of memory but this shouldn't be the problem as it run in Windows XP before I switched to version 2.5. I've already tried to remove version 2.5 and install version 2.4.3 (the one I had before), but the I get the same problem :( Has anyone every experienced such a thing? Suggestions on how to solve this? greetings, pedro rodrigues -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Fri Nov 24 21:47:35 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 24 Nov 2006 23:47:35 -0300 Subject: combining the path and fileinput modules In-Reply-To: <4565BC89.9060901@mac.com> References: <1164291336.523872.131610@h54g2000cwb.googlegroups.com> <4565BC89.9060901@mac.com> Message-ID: <7.0.1.0.0.20061124234209.03442fe0@yahoo.com.ar> At Thursday 23/11/2006 12:21, wo_shi_big_stomach wrote: > >> dir = path(/home/wsbs/Maildir) > >> for f in dir.walkfiles('*'): > >> # > >> # test: > >> # print f > > > > Are you absolutely sure that f list doesn't contain > > any path to directory, not file? > > Add this: > > > > f = filter(os.path.isfile, f) > > > > and try one more time. > >Sorry, no joy. Printing f then produces: > >rppp >rppppp >rppppp The filter should be applied to walkfiles. Something like this: dir = path(/home/wsbs/Maildir) for f in filter(os.path.isfile, dir.walkfiles('*')): # # test: # print f -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From robert.kern at gmail.com Wed Nov 15 03:02:21 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 15 Nov 2006 02:02:21 -0600 Subject: reduce to be removed? In-Reply-To: References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163288885.884417.218270@f16g2000cwb.googlegroups.com> <1163290526.013063.245130@m7g2000cwm.googlegroups.com> <1163295752.701124.322620@h54g2000cwb.googlegroups.com> <1163298336.778941.138540@m73g2000cwd.googlegroups.com> <1163347835.815187.216180@e3g2000cwe.googlegroups.com> <1163378573.018479.261660@b28g2000cwb.googlegroups.com> <1163559479.415682.138010@k70g2000cwa.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2006-11-15, Robert Kern wrote: >> Dustan wrote: >> >>> 2. While I haven't taken a good look at NumPy, my intuition tells me it >>> won't work with complex data types, which wouldn't work for me at all. >>> >>> Am I correct on that second one? >> No. numpy can make arrays of Python objects in addition to arrays of double, >> unsigned int, etc. > > Does numpy still gain you much if you have arrays of Python objects? It depends on what you want out of it. You won't get fast math, but you will get convenient multidimensional indexing, slicing, stacking, reshaping, and transposition. -- 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 lorenlightng at gmail.com Thu Nov 30 18:08:46 2006 From: lorenlightng at gmail.com (g4rlik) Date: Thu, 30 Nov 2006 15:08:46 -0800 (PST) Subject: v2.3, 2.4, and 2.5's GUI is slow for me Message-ID: <7630074.post@talk.nabble.com> I've been asking all over the place, namely different forums. I even e-mailed help at python.org about my problem, but they couldn't assist me too much. My problem is..the GUI for versions 2.3, 2.4, and 2.5 of Python run very sluggishly. When I type in them or move them around my desktop, it's very slow. I have figured out that this is because of the subprocesses running. To cope with this problem, I created an idle.txt file, and added this to the first line of it: c:\python25\python c:\python25\Lib\idlelib\idle.py -n After that I saved the extension to .bat and now when I run that file, the Python GUI opens without any subprocesses running and I have no problem. However, I'd still really like to know how I could fix this problem even more. I honestly don't understand why the GUI is so sluggish for me. The GUIs for Python version 2.2 and below run fine for me. My system specs are as follows: Windows XP Home Edition AMD Athlon XP 2800 nVidia 6800GT 1 gig of RAM If anyone else could help, that would be great. -- View this message in context: http://www.nabble.com/v2.3%2C-2.4%2C-and-2.5%27s-GUI-is-slow-for-me-tf2735011.html#a7630074 Sent from the Python - python-list mailing list archive at Nabble.com. From wo_shi_big_stomach at mac.com Wed Nov 22 23:30:40 2006 From: wo_shi_big_stomach at mac.com (wo_shi_big_stomach) Date: Wed, 22 Nov 2006 20:30:40 -0800 Subject: combining the path and fileinput modules Message-ID: <456523F0.9050803@mac.com> Newbie to python writing a script to recurse a directory tree and delete the first line of a file if it contains a given string. I get the same error on a Mac running OS X 10.4.8 and FreeBSD 6.1. Here's the script: # start of program # p.pl - fix broken SMTP headers in email files # # recurses from dir and searches all subdirs # for each file, evaluates whether 1st line starts with "From " # for each match, program deletes line import fileinput import os import re import string import sys from path import path # recurse dirs dir = path(/home/wsbs/Maildir) for f in dir.walkfiles('*'): # # test: # print f # # open file, search, change if necessary, write backup for line in fileinput.input(f, inplace=1, backup='.bak'): # check first line only if fileinput.isfirstline(): if not re.search('^From ',line): print line.rstrip('\n') # just print all other lines if not fileinput.isfirstline(): print line.rstrip('\n') fileinput.close() # end of program The script produces this error: Traceback (most recent call last): File "./p", line 22, in ? for line in fileinput.input(f, inplace=1, backup='.bak'): File "/sw/lib/python2.4/fileinput.py", line 231, in next line = self.readline() File "/sw/lib/python2.4/fileinput.py", line 300, in readline os.rename(self._filename, self._backupfilename) OSError: [Errno 21] Is a directory If I uncomment that test routine, and comment out the fileinput stuff, the program DOES print the full pathname/filename for the variable f. Many thanks for clues as to why fileinput.input doesn't like f. From fabianosidler at gmail.com Fri Nov 3 16:26:00 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Fri, 3 Nov 2006 21:26:00 +0000 Subject: getattrfunc vs. tp_methods Message-ID: <200611032126.00171.fabianosidler@gmail.com> Hello list! Writing a C extension module, which way is better to implement attribute retrieval, by a getattr function in the PyTypeObject struct or by an entry tp_methods? I don't need any black magic being executed on attribute access, so I would tend towards the tp_methods entry. Any argument against it? Greetings, Fips From bronger at physik.rwth-aachen.de Tue Nov 7 04:13:55 2006 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 07 Nov 2006 10:13:55 +0100 Subject: PIL: match for ImageMagick's display -ping Message-ID: <87ac33obzg.fsf@wilson.homeunix.com> Hall?chen! I have to extract the dimensions of many bitmap files. An old Bash script did it with ImageMagick's "display -ping ...". "-ping" means that it extracts the image dimensions efficiently. I suspect it simply doesn't read the image itself. Now the Bash script has been transformed into Python+PIL. Is there a way to get the dimensions equally efficient here, or does the PIL even do this optimisation implicitly since I never access the image bitmap itself? Thank you! Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus ICQ 264-296-646 (See http://ime.webhop.org for Jabber, MSN, etc.) From ronrsr at gmail.com Fri Nov 10 12:01:39 2006 From: ronrsr at gmail.com (ronrsr) Date: 10 Nov 2006 09:01:39 -0800 Subject: SyntaxError: Invalid Syntax. Message-ID: <1163178099.156160.29280@k70g2000cwa.googlegroups.com> no matter where I place this imported file,the statement after it in the main program gets a syntax error, regardless of the syntax. I think I may have changed something in this file, but I'm stuck. Can anyone help? #!/usr/local/bin/python # Copyright 2004 by Stephen Masterman #Change the db connection details here. import MySQLdb def connect(): return = MySQLdb.connect (host = "db91x.xxxx.com", user = "xxxx", passwd = "xxxxx", db = "homebase_zingers" ); From fredrik at pythonware.com Mon Nov 6 09:10:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 06 Nov 2006 15:10:06 +0100 Subject: Is there a commas-in-between idiom? In-Reply-To: References: Message-ID: Ernesto Garc?a Garc?a wrote: > it's very common that I have a list and I want to print it with commas > in between. How do I do this in an easy manner, whithout having the > annoying comma in the end? I've collected a bunch of list pydioms and other notes here: http://effbot.org/zone/python-list.htm For formatting issues, see: http://effbot.org/zone/python-list.htm#printing From rw at smsnet.pl Thu Nov 23 09:15:36 2006 From: rw at smsnet.pl (Rob Wolfe) Date: 23 Nov 2006 06:15:36 -0800 Subject: combining the path and fileinput modules In-Reply-To: References: Message-ID: <1164291336.523872.131610@h54g2000cwb.googlegroups.com> wo_shi_big_stomach wrote: > Newbie to python writing a script to recurse a directory tree and delete > the first line of a file if it contains a given string. I get the same > error on a Mac running OS X 10.4.8 and FreeBSD 6.1. > > Here's the script: > > # start of program > > # p.pl - fix broken SMTP headers in email files > # > # recurses from dir and searches all subdirs > # for each file, evaluates whether 1st line starts with "From " > # for each match, program deletes line > > import fileinput > import os > import re > import string > import sys > from path import path > > # recurse dirs > dir = path(/home/wsbs/Maildir) > for f in dir.walkfiles('*'): > # > # test: > # print f Are you absolutely sure that f list doesn't contain any path to directory, not file? Add this: f = filter(os.path.isfile, f) and try one more time. > # > # open file, search, change if necessary, write backup > for line in fileinput.input(f, inplace=1, backup='.bak'): > # check first line only > if fileinput.isfirstline(): > if not re.search('^From ',line): > print line.rstrip('\n') > # just print all other lines > if not fileinput.isfirstline(): > print line.rstrip('\n') > fileinput.close() > # end of program -- HTH, Rob From apardon at forel.vub.ac.be Wed Nov 8 08:24:30 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 8 Nov 2006 13:24:30 GMT Subject: please help with optimisation of this code - update of given table according to another table References: <1162981094.820174.65440@b28g2000cwb.googlegroups.com> Message-ID: On 2006-11-08, Farraige wrote: > > ... > > The main part of my algorithm now looks something like ... > > merge(t1, t2, keyColumns, columnsToBeUpdated) > > ....... > > for row_t1 in t1: > for row_t2 in t2: > if [row_t1[i] for i in keyColumns] == [row_t2[j] for j > in keyColumns]: > # the keys are the same > for colName in columnsToBeUpdated: > row_t1[colName] = row_t2[colName] > > # go outside the inner loop - we found a row with > # the same key in the table > break > > In my algorithm I have 2 for loops and I have no idea how to optimise > it (maybe with map? ) > I call this method for very large data and the performance is a > critical issue for me :( > > I will be grateful for any ideas One idea would be to precompute the list comprehensions in the if test. p2 = [[row_t2[i] for i in keyColums] for row_t2 in t2] for row_t1 in t1: proj1 = [row_t1[i] for i in keyColumns] for row_t1, proj2 in izip(t2, p2): if proj1 == proj2: ... -- Antoon Pardon From john106henry at hotmail.com Fri Nov 17 13:44:02 2006 From: john106henry at hotmail.com (John Henry) Date: 17 Nov 2006 10:44:02 -0800 Subject: How fuzzy is get_close_matches() in difflib? In-Reply-To: References: <1163724049.225348.118020@h54g2000cwb.googlegroups.com> <1163737190.118975.227740@h48g2000cwc.googlegroups.com> <1163746781.666937.63970@h48g2000cwc.googlegroups.com> Message-ID: <1163789041.970477.13550@h48g2000cwc.googlegroups.com> I suppose you are right. I guess I ended up with an odd case. I was thinking that: To change "HIDE*S*ST1" to "HIDE*D*ST1", all you do is remove the "*S*" from the source and the "*D*" from the target. In order to change "HIDE*SC*T1" to "HIDE*DS*T1", I thought you have to remove 2 characters *SC* from the source. Then I realize that it's not true. If you remove the "C" from the source, and the "D" from the *DS* of the destination, it's a match (!) So, yes, they have the same distance! Antoon Pardon wrote: > On 2006-11-17, John Henry wrote: > > I encountered a case where I am trying to match "HIDESST1" and > > "HIDESCT1" against ["HIDEDST1", "HIDEDCT1", "HIDEDCT2", "HIDEDCT3"] > > > > Well, they both hit "HIDEDST1" as the first match which is not exactly > > the result I was looking for. I don't understand why "HIDESCT1" would > > not hit "HIDEDCT1" as a first choice. > > H I D E D S T 1 H I D E D C T 1 > > H . . > I . . > D . . > E . . > S . > C . > T . . > 1 . . > > As far as I can see the distance of HIDEDCT1 to HIDESCT1 is > the same as the distance of HIDEDCT1 to HIDEDST1. In both > cases you have to remove one character from the target as well > as one character from the candidate in order to get the > same substring. > > -- > Antoon Pardon From timothy at open-networks.net Tue Nov 14 03:58:28 2006 From: timothy at open-networks.net (timmy) Date: Tue, 14 Nov 2006 18:58:28 +1000 Subject: deleteing item from a copy of a list Message-ID: <455984b5@quokka.wn.com.au> i make a copy of a list, and delete an item from it and it deletes it from the orginal as well, what the hell is going on?!?!?! #create the staff copy of the roster Roster2 = [] for ShiftLine in Roster: #delete phone number from staff copy Roster2.append(ShiftLine) del Roster2[len(Roster2)-1][1] Roster2 should have nothing to do with Roster, right??? doing a print of both lists confirms that the phone number has been removed from both From fredrik at pythonware.com Thu Nov 16 05:11:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 11:11:35 +0100 Subject: lxml/ElementTree and .tail In-Reply-To: <1163671192.876928.35960@f16g2000cwb.googlegroups.com> References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> Message-ID: Paul Boddie wrote: >> Yes, it is. Just look at the API. It's an attribute of an Element, isn't it? >> What other API do you know where removing an element from a data structure >> leaves part of the element behind? > > I guess it depends on what you regard an element to be... Stefan said "Element", not "element". "Element" is a class in the "ElementTree" module, which can be used to *represent* an XML element in an XML infoset, including all the data *inside* the XML element, and any data *between* that XML element and the next one (which is always character data, of course). It's not very difficult, really; especially if you, as Stefan said, think in infoset terms rather "a sequence of little piggies" terms. From dickinsm at gmail.com Wed Nov 29 18:33:05 2006 From: dickinsm at gmail.com (dickinsm at gmail.com) Date: 29 Nov 2006 15:33:05 -0800 Subject: Remarkable results with psyco and sieve of Eratosthenes In-Reply-To: <1164837289.295731.178070@h54g2000cwb.googlegroups.com> References: <1164837289.295731.178070@h54g2000cwb.googlegroups.com> Message-ID: <1164843185.361082.146740@16g2000cwy.googlegroups.com> > BTW, can this code be made any more efficient? I'm not sure, but the following code takes around 6 seconds on my 1.2Ghz iBook. How does it run on your machine? def smallPrimes(n): """Given an integer n, compute a list of the primes < n""" if n <= 2: return [] sieve = range(3, n, 2) top = len(sieve) for si in sieve: if si: bottom = (si*si - 3)//2 if bottom >= top: break sieve[bottom::si] = [0] * -((bottom-top)//si) return [2]+filter(None, sieve) smallPrimes(10**7) > > ============ > > #!/usr/bin/python -OO > import math > import sys > import psyco > > psyco.full() > > def primes(): > primes=[3] > for x in xrange(5,10000000,2): > maxfact = int(math.sqrt(x)) > flag=True > for y in primes: > if y > maxfact: > break > if x%y == 0: > flag=False > break > if flag == True: > primes.append(x) > primes() From sjmachin at lexicon.net Thu Nov 9 12:07:27 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Nov 2006 09:07:27 -0800 Subject: pack a three byte int In-Reply-To: References: <1163027401.386603.263030@k70g2000cwa.googlegroups.com> Message-ID: <1163092047.577688.140400@m73g2000cwd.googlegroups.com> Dave Opstad wrote: > Sorry, that should have been: > > cdb += struct.pack(">L", skip)[1:] > ">L" and ">I" produce exactly the same 4-byte result. The change from [-3:] to [1:] is a minor cosmetic improvement, but obscures the underlying ... a bit like putting mascara on a pig. I got the impression that the OP was interested in more radical improvement. Cheers, John From apardon at forel.vub.ac.be Wed Nov 29 08:08:31 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Nov 2006 13:08:31 GMT Subject: Problem with imaplib (weird result if mailbox contains a %) References: <1164727244.400677.36150@l12g2000cwl.googlegroups.com> <1164803590.454993.141050@j72g2000cwa.googlegroups.com> Message-ID: On 2006-11-29, Leo Kislov wrote: > Antoon Pardon wrote: >> On 2006-11-28, Leo Kislov wrote: >> > >> Are there more docs than at http://www.python.org/doc/. I don't find >> those very helpfull in explaining this. >> >> I also took a look at rfc 2060 and to be honest I don't find anything >> there to explain this difference. I only took a closer look at section >> 7.2.2. So maybe I should look somewehere else but after reading section >> 7.2.2. I don't understand why the list method returned a tuple for this >> mailbox instead of the following string: >> >> '(\\HasNoChildren) "/" "user/cpapen/newsletters %"' > > This is described in section 4.3. imaplib is too close to the protocol. > It should interpret response for each command separately. For example > list method could return list of tuples like: > > ("\\HasNoChildren", "/", "user/cpapen/newsletters %") > > Without this abstraction level in imaplib you have to build it > yourself. Ah yes, I'm beginning to understand now, what is going on. I also did a imap session by hand using telnet. That helped. >> >> If it is, is it fixed in later versions? >> > >> > Why don't you try to pull imaplib.py from later versions? I don't think >> > it changed that much so it should be compatible with python 2.3 >> >> I could take my hands on a 2.4 version and the result was the same. > > I was talking only about empty string response. Is it still there? > Anyway, this issue requires investigation. That could also be a bug in > the server. The empty line is still there using 2.4. This is part of the session I did by hand. It doesn't seem to be a server problem. $ telnet machine.domain imap Trying xxx.xxx.xxx.xxx... Connected to machine.domain Escape character is '^]'. * OK maxi Cyrus IMAP4 v2.2.13 server ready 0001 LOGIN ... .... 0001 OK User logged in 0002 LIST "" user/cpapen/* * LIST (\HasNoChildren) "/" "user/cpapen/Out" ... * LIST (\HasNoChildren) "/" "user/cpapen/music &- beats" * LIST (\HasNoChildren) "/" {25} user/cpapen/newsletters % * LIST (\HasNoChildren) "/" "user/cpapen/organisatie &- structuur" * LIST (\HasNoChildren) "/" "user/cpapen/sociale wetenschappen" ... Many thanks for your contribution. -- Antoon Pardon From steve at holdenweb.com Tue Nov 7 13:55:46 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Nov 2006 13:55:46 -0500 Subject: [DLC] ChiPy Monthly Meeting, Thursday 7:00 pm. In-Reply-To: <1162921007.26531.275231865@webmail.messagingengine.com> References: <1162921007.26531.275231865@webmail.messagingengine.com> Message-ID: I don't suppose there's any chance that someone might be passing Schaumberg on their way to this meeting? I'm teaching there, and a ride would avoid me having to rent a car (and hence increase the probability I'd make it). regards Steve bray at sent.com wrote: > Thursday November 9 2006. 7:00 pm. > > This may be our best meeting yet. This is our regular Thurs. meeting. In > addition stay tuned for a special meeting to welcome Ed Leafe > http://chipy.org/EdOnDabo. > > Please ping the list to tell us what you want to address in your > lightning talk. Lets try to get one talk from each brave soul for about > 5 minutes > a piece. > > Topics > ------ > > - Python Mock Library - fawad > - Web log generation and parsing > - lightning talks > > Location > -------- > > Daisychain - 2159 W 21st Pl, Chicago il 60608 http://www.dai5ychain.net/ > map - http://tinyurl.com/ybdcxb > > About ChiPy > ----------- > > ChiPy is a group of Chicago Python Programmers, l33t, and n00bs. > Meetings are held monthly at various locations around Chicago. > Also, ChiPy is a proud sponsor of many Open Source and Educational > efforts in Chicago. Stay tuned to the mailing list for more info. > > ChiPy website: > ChiPy Mailing List: > Python website: > > --- > > > _______________________________________________ > DLC mailing list > DLC at mailman.depaul.edu > http://mailman.depaul.edu/mailman/listinfo/dlc > http://linux.depaul.edu/ > -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From meyer at acm.org Fri Nov 3 06:30:04 2006 From: meyer at acm.org (Andre Meyer) Date: Fri, 3 Nov 2006 12:30:04 +0100 Subject: Feature Request: Py_NewInterpreter to create separate GIL (branch) In-Reply-To: References: Message-ID: <7008329d0611030330r3975076ctcbd341dc9e962318@mail.gmail.com> Hi all Strange enough, there does not even seem to be interest in removing the GIL in Python 3000. For some interesting answers on this topic you may read through the thread "Kill GIL" on the py3k mailing list archives: . kind regards Andr? On 11/3/06, robert wrote: > > Feature Request: Py_NewInterpreter to create separate GIL (branch) > > Daniel Dittmar wrote: > > robert wrote: > >> I'd like to use multiple CPU cores for selected time consuming Python > >> computations (incl. numpy/scipy) in a frictionless manner. > >> > >> Interprocess communication is tedious and out of question, so I > >> thought about simply using a more Python interpreter instances > >> (Py_NewInterpreter) with extra GIL in the same process. > > > > If I understand Python/ceval.c, the GIL is really global, not specific > > to an interpreter instance: > > static PyThread_type_lock interpreter_lock = 0; /* This is the GIL */ > > > > Thats the show stopper as of now. > There are only a handfull funcs in ceval.c to use that very global lock. > The rest uses that funcs around thread states. > > Would it be a possibilty in next Python to have the lock separate for each > Interpreter instance. > Thus: have *interpreter_lock separate in each PyThreadState instance and > only threads of same Interpreter have same GIL? > Separation between Interpreters seems to be enough. The Interpreter runs > mainly on the stack. Possibly only very few global C-level resources would > require individual extra locks. > > Sooner or later Python will have to answer the multi-processor question. > A per-interpreter GIL and a nice module for tunneling Python-Objects > directly between Interpreters inside one process might be the answer at the > right border-line ? Existing extension code base would remain compatible, as > far as there is already decent locking on module globals, which is the the > usual case. > > Robert > -- > http://mail.python.org/mailman/listinfo/python-list > -- Dr. Andre P. Meyer http://python.openspace.nl/meyer TNO Defence, Security and Safety http://www.tno.nl/ Delft Cooperation on Intelligent Systems http://www.decis.nl/ Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Sat Nov 11 19:55:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Nov 2006 01:55:35 +0100 Subject: explicit self revisited In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: >> one article at a time. who's going to be the first one to argue that >> Python needs a goto statement ? >> > Especially since there is a comefrom ah, good point. I've updated the FAQ. From sturlamolden at yahoo.no Wed Nov 8 15:16:24 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 8 Nov 2006 12:16:24 -0800 Subject: Python deployment options. In-Reply-To: <1162995465.419376.229440@f16g2000cwb.googlegroups.com> References: <1162982262.010438.99260@f16g2000cwb.googlegroups.com> <1162985073.163257.110180@m73g2000cwd.googlegroups.com> <1162995465.419376.229440@f16g2000cwb.googlegroups.com> Message-ID: <1163016983.930850.50610@h54g2000cwb.googlegroups.com> Fuzzyman wrote: > I think that is an incorrect reading of the thread. > > The *Python* developers need a valid Visual Studio license to > redistribute msvcr71.dll. > > When you build an app with py2exe you are just bundling Python with > your application and so don't need the license. Here is a summary of my understanding of the "problem", mind you that I am not a lawayer: The Python.org developers use a properly licensed VC7 to build Python. Under the EULA they can redistribute msvcr71.dll along with Python. Anyone can distribute Python from Python.org, and msvcr71.dll is a part of this software. Thus, it is at least legally to distribute a Python MSI installer from Python.org. If you make a Python program, you can distribute Python along with the program. I.e. you don't need a VC7 license to sell software that someone else has made and includes msvcr71.dll. For Py2Exe things are a bit more complicated. It rips Python.Runtime.dll from the Python directory, and renames it Python24.dll. Python24.dll then depends on msvcr71.dll. It's not obvious that one can still legally distribute msvcr71.dll along with Python24.dll, even if Python.Runtime.dll was built with a legally licensed VC7. It is possible that Python24.dll or msvcr71.dll in the process looses it status as licensee software from Python.org's VC7.The Python.org team don't care about the issue, it seems. If they did care, they could settle the issue by putting up a zip-file with Python24.dll and msvcr71.dll for download. I don't think they quite understand how important Py2Exe is on Windows. Buying a VC7 license is cheaper than paying a lawyer that understands the problem. However, even with a VC7 license you can only redistribute msvcr71.dll with software you build your self - so you need to build Python your self and not use a Python24.dll ripped from Python.org's Python distro. But then ... who cares? Microsoft wants you to make software for their OS. They even have their own version of Python for free download (aka IronPython). A MS lawyer harassing you for legal details regarding msvcr71.dll is beyond unlikely, although you never know. You can play nice and ask Microsoft for permission to put msvcr71.dll inside your Py2Exe'd Python app. Whether they will respond or grant permission I don't know. Finally, patent issues are more important when making software for a living. Are you sure nobody has a broad patent covering parts of your software? These are often held by parasitic companies that use broad software patents as spider webs to catch prey. They will suck blood from you if they can, and give you less than nothing in return, something Microsoft probably will not do. Microsoft makes and sells software, including the Windows operating system, patent sharks just thrive off their patents. Being sued by one of those are far more likely. From bearophileHUGS at lycos.com Wed Nov 22 15:46:22 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Nov 2006 12:46:22 -0800 Subject: regex problem In-Reply-To: References: Message-ID: <1164228382.661892.169220@j44g2000cwa.googlegroups.com> > > line is am trying to match is > > 1959400|Q2BYK3|Q2BYK3_9GAMM Hypothetical outer membra 29.9 0.00011 1 > > > > regex i have written is > > re.compile > > (r'(\d+?)\|((P|O|Q)\w{5})\|\w{3,6}\_\w{3,5}\s+?.{25}\s{3}(\d+?\.\d)\s+?(\d\.\d+?)') > > > > I am trying to extract 0.0011 value from the above line. > > why doesnt it match the group(4) item of the match ? > > > > any idea whats wrong with it ? I am not expert about REs yet, but I suggest you to use the re.VERBOSE and split your RE in parts, like this: example = re.compile(r"""^ \s* # must start at the beginning + optional whitespaces ( [\[\(] ) # Group 1: opening bracket \s* # optional whitespaces ( [-+]? \d+ ) # Group 2: first number \s* , \s* # optional space + comma + optional whitespaces ( [-+]? \d+ ) # Group 3: second number \s* # optional whitespaces ( [\)\]] ) # Group 4: closing bracket \s* $ # optional whitespaces + must end at the end """, flags=re.VERBOSE) This way you can debug and mantain it much better. Bye, bearophile From rridge at csclub.uwaterloo.ca Tue Nov 21 01:28:41 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 20 Nov 2006 22:28:41 -0800 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? References: <18c54$455d019b$59ad1aca$24364@news.flashnewsgroups.com> <455d507d$0$18480$9b622d9e@news.freenet.de> <3188c$455d923f$59ad1aca$4742@news.flashnewsgroups.com> <455E5D15.7030207@v.loewis.de> <3e540$4560b958$59ad1aca$32456@news.flashnewsgroups.com> <4560E3AE.5030307@v.loewis.de> <1163992410.229236.60830@e3g2000cwe.googlegroups.com> <4561515B.4060106@v.loewis.de> <1164046257.736569.267090@j44g2000cwa.googlegroups.com> <45623696.90504@v.loewis.de> Message-ID: <1164090521.578144.245440@m73g2000cwd.googlegroups.com> Martin v. L?wis wrote: > Then I would use U+E000 for escaping. Each PUA character in the > listed file name would get escaped with U+E000 in the Python > string; when the file name is converted back to the system, it > gets unescaped. How would you tell an escaped file name containing these private use characters obtain from os.listdir() from an unescaped file name containing these characters obtained from some other source? > Notice that I think this is a really unrealistic case - I expect > that all file names containing PUA characters were deliberately > crafted to investigate using PUA characters in file names. I suspect a more common case is file names containing end-user defined characters. > What Far-East multi-byte encoding uses PUA characters, > and for what characters? Pretty much all of them near as I can tell. See the following WWW page for a discusion of this issue: http://www.opengroup.or.jp/jvc/cde/ucs-conv-e.html > On no operating system I'm aware of can you pass "Unicode strings" to > open() or stat(). *sigh* I was refering to the Python functions "open() and stat() etc." just as you had in paragraph I copied those exact words from. > > On Windows you can use GetVolumeInformation()... > > On Windows, the entire issue doesn't exist: On Windows, I think you should use GetVolumeInformation() to decide whether or not os.listdir() returns Unicode or byte strings, rather than the type of the argument. >> ... but then the Python docs suggests this > > os.listdir() Unicode feature doesn't work on Macintosh systems anyways. > > Either the docs are wrong, or you are misinterpreting them. It works > just fine in practice. As the original poster in this thread wrote, the docs say: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects The implication being that Macintosh systems don't support this feature. > > That's the problem here, there's no > > encoding associated Unix filenames, they're just byte strings. > > Can you please quote chapter and verse of the POSIX spec that says > so? I said Unix, not POSIX. In practice, Unix systems don't associate an encoding with filenames, and any byte value other than '/' or '\0' is permitted in a filename. Not that it really matters, Python byte strings are also the natural way to respresent file names stored in a unspecified encoding. Ross Ridge From python at rcn.com Tue Nov 14 15:16:09 2006 From: python at rcn.com (Raymond Hettinger) Date: 14 Nov 2006 12:16:09 -0800 Subject: multi split function taking delimiter list In-Reply-To: <1163534200.476392.303680@m73g2000cwd.googlegroups.com> References: <1163534200.476392.303680@m73g2000cwd.googlegroups.com> Message-ID: <1163535369.374279.15350@f16g2000cwb.googlegroups.com> martinskou at gmail.com wrote: > Hi, I'm looking for something like: > > multi_split( 'a:=b+c' , [':=','+'] ) > > returning: > ['a', ':=', 'b', '+', 'c'] > > whats the python way to achieve this, preferably without regexp? I think regexps are likely the right way to do this kind of tokenization. The string split() method doesn't return the split value so that is less than helpful for your application: 'a=b'.split() --> ['a', 'b'] The new str.partition() method will return the split value and is suitable for successive applications: 'a:=b+c'.partition(':=') --> ('a', ':=', 'b+c') FWIW, when someone actually does want something that behaves like str.split() but with multiple split values, one approach is to replace each of the possible splitters with a single splitter: def multi_split(s, splitters): first = splitters[0] for splitter in splitters: s = s.replace(splitter, first) return s.split(first) print multi_split( 'a:=b+c' , [':=','+'] ) Raymond From XX.XmcX at XX.XmclaveauX.com Fri Nov 3 14:47:08 2006 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Fri, 03 Nov 2006 20:47:08 +0100 Subject: Javascript is turning into Python?! References: <7xwt6dkn50.fsf@ruckus.brouhaha.com> <1162540289.138892.206990@b28g2000cwb.googlegroups.com> Message-ID: Hi! > (ECMAscript), then, well I haven't seen any progress there. 1) in IE-7, the last release (of JScript) has few evolutions (more important, a new garbage collector) 2) in Windows, with Active-Scripting, it's possible to integrate JScript in Python, call JScript's functions from Python's code, call Python's functions from JScript's code, etc. -- @-salutations Michel Claveau From jgodoy at gmail.com Mon Nov 6 05:29:49 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Mon, 06 Nov 2006 08:29:49 -0200 Subject: Python Distilled References: <1162790565.418382.237050@m73g2000cwd.googlegroups.com> Message-ID: <87vels3m1u.fsf@gmail.com> Marc 'BlackJack' Rintsch writes: > In <1162790565.418382.237050 at m73g2000cwd.googlegroups.com>, Simon Wittber > wrote: > >> I'd also like to remove any deprecated or stuff which is left in for >> backwards functionality (eg Classic classes). > > Classic classes are still needed for exceptions: > >>>> class E(object): > ... pass > ... >>>> raise E > Traceback (most recent call last): > File "", line 1, in > TypeError: exceptions must be classes, instances, or strings (deprecated), > not type On the other hand... >>> import exceptions >>> class E(exceptions.Exception): ... pass ... >>> raise E Traceback (most recent call last): File "", line 1, in ? __main__.E >>> This also has the advantage to let it explicit in the code that E is an exception. -- Jorge Godoy From bearophileHUGS at lycos.com Sat Nov 4 03:43:57 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 4 Nov 2006 00:43:57 -0800 Subject: Defaultdict and speed In-Reply-To: <1162616241.354248.70220@f16g2000cwb.googlegroups.com> References: <1162542563.386682.3090@b28g2000cwb.googlegroups.com> <1162616241.354248.70220@f16g2000cwb.googlegroups.com> Message-ID: <1162629837.024248.94910@h54g2000cwb.googlegroups.com> Klaas wrote: > Benchmarks? There is one (fixed in a succesive post) in the original thread I was referring to: http://groups.google.com/group/it.comp.lang.python/browse_thread/thread/aff60c644969f9b/ If you want I can give more of them (and a bit less silly, with strings too, etc). def ddict(n): t = clock() d = defaultdict(int) for i in xrange(n): d[i] += 1 print round(clock()-t, 2) def ndict(n): t = clock() d = {} for i in xrange(n): if i in d: d[i] += 1 else: d[i] = 1 print round(clock()-t, 2) ddict(300000) ndict(300000) > (and slowing down other uses of the class) All it has to do is to cheek if the default_factory is an int, it's just an "if" done only once, so I don't think it slows down the other cases significantly. > especially when the faster alternative is so easy to code. The faster alternative is easy to create, but the best faster alternative can't be coded, because if you code it in Python you need two hash accesses, while the defaultdict can require only one of them: if n in d: d[n] += 1 else: d[n] = 1 >If that performance difference matters, With Python it's usually difficult to tell if some performance difference matters. Probably in some programs it may matter, but in most other programs it doesn't matter. This is probably true for all the performance tweaks I may invent in the future too. > you would likely find more fruitful > gains in coding it in c, using PyDict_SET I've just started creating a C lib for related purposes, I'd like to show it to you all on c.l.p, but first I have to find a place to put it on :-) (It's not easy to find a suitable place, it's a python + c + pyd, and it's mostly an exercise). Bye, bearophile From guettli.usenet at thomas-guettler.de Mon Nov 20 11:34:30 2006 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 20 Nov 2006 16:34:30 GMT Subject: OODB vs RDBMS Message-ID: <4se3omFv6reaU1@mid.individual.net> Hi, most of the time I use ZODB/Durus to store my data. I like it, but I know that it has some weaknesses: - only accesible from python - I need to code your indexes for fast searching yourself. I think about using a RDBMS for the next project. What I don't like about RDBMS: If you need a list of values you need to create a new table. Example: If you want to store several email addresses of one customer, you need to create a new table. Since the namespace if tablenames is flat, you soon have so many tables, that it is hard to browse them. Postgres has extensions which allows you to store arrays in a column. Is this supported by the python binding? Are there other databases which support this? Are there OR-mappers (object relational mappers) which support lists in a column? How is the unicode support of the python bindings to RDBMSs? I don't want to convert the results of a query to unicode myself. Can you insert unicode strings into a SELECT statement? Which database supports fulltext searches with a customized word normalization? (All should be the same: str. str stra?e, strasse) Which OR-mapper do you suggest? Are there OR-mappers which support this: Subobjects are fetched automatically while you access the object tree? Example: One customer has N TroubleTicketItems: customerobj=get_customer(...) # First SELECT for ticket in customerobj.tickets: # (*) ... (*) Second SELECT gets executed only if needed. I now this message is vague, but maybe we can discuss the pros/cons of "OODB vs RDBMS" Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From samgurung at gmail.com Tue Nov 28 04:32:34 2006 From: samgurung at gmail.com (linuxfreak) Date: 28 Nov 2006 01:32:34 -0800 Subject: Libgmail In-Reply-To: References: <1164703460.303062.58620@80g2000cwy.googlegroups.com> Message-ID: <1164706353.955200.128330@l39g2000cwd.googlegroups.com> Funny enough I find the same "Google" in my browser too. and if my memory serves me correct I did the same search which you allude to. It is only after series of exhaustive searches rummaging through websites with incomplete (or non existent ) docs that i posed the question here.... :) thanks for the suggestion anyway.... Jussi Salmela wrote: > linuxfreak wrote: > > hi guys, > > > > just starting out on python and libgmail... any documentation for > > libgmail outthere... basically what i want to do is develop an > > application to use gmail like and ftp server... should be able to > > upload files and download them as well.... > > > > thanks > > > > My browser has this amazing thing called Google installed. It's a kind > of search facility with which I can search through Internet to find > information. > > By searching for libgmail it gives me about 158000 places to read > through but if I were you I'd start at the top which is > libgmail.sourceforge.net > > HTH, > Jussi From vito.detullio at gmail.com Mon Nov 13 15:11:24 2006 From: vito.detullio at gmail.com (ZeD) Date: Mon, 13 Nov 2006 20:11:24 GMT Subject: tab compleation input References: <1163434288.421441.48320@f16g2000cwb.googlegroups.com> Message-ID: Eli Criffield wrote: > Here is what i want to do. I have a question in my program, and i want > to do tab completion for the valid answers. I think you may "play" width curses library: readline() read... while you input a "newline", but you need to catch single keys (the "TAB" key, foremost) -- Under construction From gagsl-py at yahoo.com.ar Wed Nov 29 05:31:38 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 29 Nov 2006 07:31:38 -0300 Subject: Small prog question from a newbie: abt variables in a function definition In-Reply-To: References: Message-ID: <7.0.1.0.0.20061129071220.053c7d90@yahoo.com.ar> At Wednesday 29/11/2006 06:48, B Shyam Sundar wrote: >I am a newbie as far as python is concerned ... I am trying to write >a code for playing bridge in obj oriented manner .. > >Well ... i have this small problem: > >class hand: > def __init__(self,set_of_cards=[]): > self.set_of_cards=set_of_cards > card_played_flag =0 > def play(played_card): > for i in self.set_of_cards: > if self.set_of_cards[i] == played_card: > self.set_of_cards.remove (played_card) > def sort_hand(): > for i in self.set_of_cards: > for j in self.set_of_cards: > if self.set_of_cards[j].face self.set_of_cards > [j],self.set_of_cards[i]=self.set_of_cards[i],self.set_of_cards[j] > for i in self.set_of_cards: > for j in self.set_of_cards: > if self.set_of_cards[j].suit >self.set_of_cards[j],self.set_of_cards[i]=self.set_of_cards[i],self.set_of_cards[j] > >I have created card as a class with the attributes of suit face so >.. card(suit,face) > >So my question is this --- > >The compiler doesnt recognise that there is self.set_of_cards[j] can >be a card. It gives a syntax error. >Also I have not created any instance of the class (Can that be a problem) (The compiler knows very few about your cards... Python is a very dynamic language, a lot of things happens at runtime) Without compiling your example, I can see these syntax errors: 1) In Python indentation matters. sort_hand must have the same indentation as play (and the other methods). 2) Syntax for the if statement - you need a final ":" if condition: something if condition: do something and do other thing and do another thing >So how do i fix this? >Also can I specify that the list set_of_cards has only card objects? >IF yes how? Short answer: don't bother. (Yes, you *could* inherit from list and restrict the contained items, but it's seldom used). You don't have to sort manually, this should work: set_of_cards.sort(key=lambda card: (card.suit,card.face)) And don't use a mutable initializer in __init__: either use an empty tuple () or use None and check for it in the method body: def __init__(self, set_of_cards=None): if set_of_cards is None: set_of_cards=[] self.set_of_cards = set_of_cards -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From mike.klaas at gmail.com Fri Nov 17 00:55:23 2006 From: mike.klaas at gmail.com (Klaas) Date: 16 Nov 2006 21:55:23 -0800 Subject: dict.reserve and other tricks In-Reply-To: <1163724294.126102.216870@e3g2000cwe.googlegroups.com> References: <1163724294.126102.216870@e3g2000cwe.googlegroups.com> Message-ID: <1163742923.680092.264030@j44g2000cwa.googlegroups.com> bearophileHUGS at lycos.com wrote: > I have started doing practice creating C extensions for CPython, so > here are two ideas I have had, possibly useless. > > If you keep adding elements to a CPython dict/set, it periodically > rebuilds itself. So maybe dict.reserve(n) and a set.reserve(n) methods > may help, reserving enough (empty) memory for about n *distinct* keys > the programmer wants to add to the dict/set in a short future. I have > seen that the the C API of the dicts doesn't allow this, and I don't > know if this can be implemented modifying the dicts a bit. Do you think > this may be useful? It has been proposed before and rejected. How often is dict creation a bottleneck in python apps? I'd guess not often. Do you know of any examples Optimize space use also isn't terribly compelling, as a "tight" dict can be created from a "loose" dict d using dict(d). <> > Most of the times such functions are good enough, but sometimes the > dicts are big, so to reduce memory used I remove keys in place: > > def filterdict(pred, indict): > todel = [k for k,v in indict.iteritems() if not pred(k,v)] > for key in todel: > del indict[key] <> > But doing the same thing while iterating on the dict may be faster and > use even less memory. Well, you can reduce the memory usage to virtually nothing by using a generator expression rather than list comprehension. > This iteration&deletion capability is probably not safe enough to be > used inside Python programs, but a compiled C module with a function > that works like that filterdict (and deletes while iterating) may be > created, and its use is safe from Python programs. <> > >The dictionary p should not be mutated during iteration. It is safe (since Python 2.1) to modify the values of the keys as you iterate over the dictionary, but only so long as the set of keys does not change.< > > Do you think it may be useful to create to create such C filterdict > function that deletes while iterating? (To create such function it > probably has to bypass the CPython dict API). Such a beast would be fiendish to write, I think. Remember, arbitrary python code can be executed by __hash__ and deleting (DECREF) python objects. -Mike From filipwasilewski at gmail.com Fri Nov 3 06:38:43 2006 From: filipwasilewski at gmail.com (Filip Wasilewski) Date: 3 Nov 2006 03:38:43 -0800 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: Message-ID: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> robert wrote: > I'd like to use multiple CPU cores for selected time consuming Python computations (incl. numpy/scipy) in a frictionless manner. > > Interprocess communication is tedious and out of question, so I thought about simply using a more Python interpreter instances (Py_NewInterpreter) with extra GIL in the same process. > I expect to be able to directly push around Python Object-Trees between the 2 (or more) interpreters by doing some careful locking. I don't want to discourage you but what about reference counting/memory management for shared objects? Doesn't seem fun for me. Take a look at IPython1 and it's parallel computing capabilities [1, 2]. It is designed to run on multiple systems or a single system with multiple CPU/multi-core. It's worker interpreters (engines) are loosely coupled and can utilize several MPI modules, so there is no low-level messing with GIL. Although it is work in progress it already looks quite awesome. [1] http://ipython.scipy.org/moin/Parallel_Computing [2] http://ipython.scipy.org/moin/Parallel_Computing/Tutorial fw From lorenzo at diespammerhethurmans.com Sun Nov 5 15:49:27 2006 From: lorenzo at diespammerhethurmans.com (Lorenzo Thurman) Date: Sun, 05 Nov 2006 14:49:27 -0600 Subject: NEWBIE: Script help needed In-Reply-To: <1162716143.747535.109270@h48g2000cwc.googlegroups.com> References: <1162716143.747535.109270@h48g2000cwc.googlegroups.com> Message-ID: Thanks for the reply, but I know there is something wrong with the command, I'm just not sure how to troubleshoot it. Anyway, I can execute all of the commands from the command line, but only 3 fails when run from within the script. I'll take a look at the link. Nick Vatamaniuc wrote: > If the other commands work but 3) doesn't, it means there is something > different (wrong?) with the command. > > So try running 3) , then one of the other ones and see the difference. > > > The getCommandOutput() , I suspect, just waits for the data from the > actual command and the command is not returning anything. It could be > because it just takes way too long (I am not familiar with Gentoo, so > not sure if emerge world takes 1 second or 24 hours...) or perhaps the > "emerge -uvp world" stops at some point and is waiting for input (a > command prompt like "are you sure you want to do this [Y/n]?" > > For more in depth on subprocesses in Python take a look at the > subprocess module: > http://docs.python.org/lib/module-subprocess.html > > Hope this helps, > Nick V. > > > > Lorenzo wrote: >> I have this script that I want to use weekly to send me email with >> information regarding disk space and available upgrades for my system. >> This script is actually a learning tool for me as I learn Python. The >> problem I've run into has me stumped and I need some help. What happens >> is when the script runs it does these things, parses the result and >> appends that to an html string: >> >> 1) checks disk space by using df -t reiserfs >> 2) runs time emerge --sync >> 3) runs emerge -uvp world >> 4) runs emerge -uv --fetchonly world >> >> The 'emerge' command is a Gentoo specific one. If I remove step 3), >> everything else runs just fine, the email is sent and I receive what I >> expect. But when step 3) is allowed to run, even if its the only command >> that runs, it hangs somewhere in the function getCommandOutput. If I try >> and debug the command, it appears to hang on this line: >> err = child.wait() >> >> I suspect a race condition, but I'm not sure how to proceed, can someone >> lend me a hand. Here is the script I wrote, I got the command >> getCommandOutput from this site: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52296 >> TIA >> >> [code] >> #!/usr/bin/python >> >> ################################ >> ### NEED TO RUN THIS AS ROOT ### >> ### EMERGE SYNC REQUIRES THIS ### >> ################################ >> import os, re, smtplib, MimeWriter, mimetools, cStringIO, popen2, fcntl, >> select, pdb >> >> cmd = 'df -t reiserfs' >> finalList = [] >> theOutput = [] >> >> text = "This realy should be in HTML" >> >> >> html = "\ >> \ >> > charset=iso-8859-1\">\ >> \ >>
Disk Utilization on >> Hedley:
" >> >> out = cStringIO.StringIO() >> writer = MimeWriter.MimeWriter(out) >> txtin = cStringIO.StringIO(text) >> >> >> def createhtmlmail (html, text, subject): >> """Create a mime-message that will render HTML in popular >> MUAs, text in better ones""" >> import MimeWriter >> import mimetools >> import cStringIO >> >> out = cStringIO.StringIO() # output buffer for our message >> htmlin = cStringIO.StringIO(html) >> txtin = cStringIO.StringIO(text) >> >> writer = MimeWriter.MimeWriter(out) >> # >> # set up some basic headers... we put subject here >> # because smtplib.sendmail expects it to be in the >> # message body >> # >> writer.addheader("Subject", subject) >> writer.addheader("MIME-Version", "1.0") >> >> writer.addheader("From", "Hedley at myserver.com") >> writer.addheader("To", "lorenzo at myserver.com") >> # >> # start the multipart section of the message >> # multipart/alternative seems to work better >> # on some MUAs than multipart/mixed >> # >> writer.startmultipartbody("alternative") >> writer.flushheaders() >> # >> # the plain text section >> # >> subpart = writer.nextpart() >> subpart.addheader("Content-Transfer-Encoding", "quoted-printable") >> pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) >> mimetools.encode(txtin, pout, 'quoted-printable') >> txtin.close() >> # >> # start the html subpart of the message >> # >> subpart = writer.nextpart() >> subpart.addheader("Content-Transfer-Encoding", "quoted-printable") >> # >> # returns us a file-ish object we can write to >> # >> pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) >> mimetools.encode(htmlin, pout, 'quoted-printable') >> htmlin.close() >> # >> # Now that we're done, close our writer and >> # return the message body >> # >> writer.lastpart() >> msg = out.getvalue() >> out.close() >> print msg >> return msg >> >> def makeNonBlocking(fd): >> fl = fcntl.fcntl(fd, fcntl.F_GETFL) >> try: >> fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY) >> except AttributeError: >> fcntl.fcntl(fd, fcntl.F_SETFL, fl | fcntl.FNDELAY) >> >> >> def getCommandOutput(command): >> theOutput = [] >> child = popen2.Popen3(command, 1) # capture stdout and stderr from >> command >> child.tochild.close() # don't need to talk to child >> outfile = child.fromchild >> outfd = outfile.fileno() >> errfile = child.childerr >> errfd = errfile.fileno() >> makeNonBlocking(outfd) # don't deadlock! >> makeNonBlocking(errfd) >> outdata = errdata = '' >> outeof = erreof = 0 >> while 1: >> ready = select.select([outfd,errfd],[],[]) # wait for input >> if outfd in ready[0]: >> outchunk = outfile.read() >> if outchunk == '': outeof = 1 >> outdata = outdata + outchunk >> if errfd in ready[0]: >> errchunk = errfile.read() >> if errchunk == '': erreof = 1 >> errdata = errdata + errchunk >> if outeof and erreof: break >> select.select([],[],[],.1) # give a little time for buffers to fill >> err = child.wait() >> if err != 0: >> raise RuntimeError, '%s failed w/ exit code %d\n%s' % (command, err, >> errdata) >> theOutput.append(outdata) >> theOutput.append(errdata) >> return theOutput >> >> >> #Run df and get the disk info >> output = os.popen(cmd) >> >> # match two or more spaces, the header line has a sngle >> # space between the 'Mouted on' field >> # We need to keep those together >> # The other spaces are the separation in the field headers >> # To get the output from df down to just the field headers >> # and the data, we need to match 2 or more spaces >> # -1 eliminates the \n at the end of output. >> # We'll get it back when we write each line to the >> # mail message, I suspect >> >> html += "" >> >> for lines in output.readlines(): >> >> p = re.compile('\ +') >> formattedText = p.subn(' ', lines[:-1], 5) >> html += formattedText[0] + '
' >> >> html += "
" >> >> mydata = getCommandOutput("time emerge --sync") >> >> >> p = re.compile('\ +') >> p.subn(' ', mydata[1])[0] >> p = re.compile('\n') >> string = (p.subn('
', mydata[1]))[0] >> >> html += "

Sync Time: " + "
" + >> "
" + "" + string + "" >> >> >> mydata = "" >> mydata = getCommandOutput("emerge -uvp world") >> >> p = re.compile('\ +') >> (p.subn(' ', mydata[0]))[0] >> p = re.compile('\n') >> html += "" + (p.subn('
', mydata[0]))[0] + >> "
" >> >> >> >> try: >> getCommandOutput('emerge -uv --fetchonly world') >> html += "
Fetch completed >> successfuly!
" >> except RuntimeError: >> html += "< font color='Red'>
******Fetch did not complete >> successfully!*********" >> >> html+= ' ' >> >> out = cStringIO.StringIO() >> writer = MimeWriter.MimeWriter(out) >> txtin = cStringIO.StringIO("This should be in HTML") >> subject = "Emerge info and disk utilization on Hedley" >> message = createhtmlmail(html, text, subject) >> server = smtplib.SMTP("hedley") >> server.sendmail('Hedley at myserver.com', 'lorenzo at myserver.com', message) >> server.quit() >> [/code] >> >> -- >> "My Break-Dancing days are over, but there's always the Funky Chicken" >> --The Full Monty > From python.list at tim.thechases.com Tue Nov 21 16:45:42 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 21 Nov 2006 15:45:42 -0600 Subject: Is there a list comprehension for this? In-Reply-To: <1164143944.874745.19470@f16g2000cwb.googlegroups.com> References: <1164143944.874745.19470@f16g2000cwb.googlegroups.com> Message-ID: <45637386.3030503@tim.thechases.com> > dw = [ 1, -1.1, +1.2 ] > > Suppose I want to create a list 'w' that is defined as > > w[0] = dw[0], > w[1] = w[0] + dw[1], > w[2] = w[1] + dw[2] > > Is there a list comprehension or map expression to do it in one or 2 > lines. Well, while it's not terribly efficient, you can do something like w = [sum(dw[:i]) for i in xrange(1,len(dw)+1)] Or, if you need the efficiencies for larger len(dw) values, you could do something like >>> def f(x): ... i = 0 ... for item in x: ... i += item ... yield i ... >>> list(i for i in f(dw)) [1, -0.10000000000000009, 1.0999999999999999] Just a few ideas, -tkc From Laundro at gmail.com Mon Nov 27 04:12:43 2006 From: Laundro at gmail.com (LaundroMat) Date: 27 Nov 2006 01:12:43 -0800 Subject: reading id3 tags with python In-Reply-To: <1164386522.229372.116120@l12g2000cwl.googlegroups.com> References: <1164328566.089711.89870@l12g2000cwl.googlegroups.com> <1164354948.000349.52170@m7g2000cwm.googlegroups.com> <1164386522.229372.116120@l12g2000cwl.googlegroups.com> Message-ID: <1164618762.975659.241520@j72g2000cwa.googlegroups.com> On Nov 24, 5:42 pm, "jeff" wrote: [snip] > and what do you mean by 'id3reader' cant do directories? > my for loop just does each file in the dirextory It's just a friendly warning that you shouldn't suppose that all that is scanned are indeed files, and not directories. From boney.dalwani at gmail.com Tue Nov 14 05:25:37 2006 From: boney.dalwani at gmail.com (boney) Date: 14 Nov 2006 02:25:37 -0800 Subject: mod_python installation problem ..severity High Message-ID: <1163499937.692984.101720@h48g2000cwc.googlegroups.com> hello All, I am totally unknown to python language.. i need to install mod_python to embed python interpreter with the Apache server, in order to use Trac with Apache Web Server i am using : Python 2.4.3, apache 2.0.50 for windows, mod_python-3.2.10.win32-py2.4-apache2.0 (windows installer) after installing the packages i added the following lines to the httpd.conf file : LoadModule python_module modules/mod_python.so in order to test mod_python installation i added to following line to the httpd.conf file AddHandler mod_python .py PythonHandler mptest PythonDebug On within the htdocs/test folder there is mptest.py file with the following contents from mod_python import apache def handler(req): req.content_type = 'text/plain' req.write("Hello World!") return apache.OK On doing this and duly following the installation and testing instructions at www.modpython.org and then pointing the url as http://localhost/test/mptest.py, i get the following error on the server log file: [Tue Nov 14 15:17:47 2006] [error] make_obcallback: could not import mod_python.apache.\n [Tue Nov 14 15:17:47 2006] [error] make_obcallback: Python path being used "['C:\\\\Program Files\\\\Apache Group\\\\Apache2\\\\bin\\\\python24.zip', '.\\\\DLLs', '.\\\\lib', '.\\\\lib\\\\plat-win', '.\\\\lib\\\\lib-tk', 'C:\\\\Program Files\\\\Apache Group\\\\Apache2\\\\bin']". [Tue Nov 14 15:17:47 2006] [error] python_handler: no interpreter callback found. [Tue Nov 14 15:17:47 2006] [error] [client 127.0.0.1] python_handler: Can't get/create interpreter. On one of the forum i got the following feedback regarding this error:- This one seems to occur on all platforms with similar frequency, and is usually related to having python multiple versions on the same system.The solution is to adjust that PATH apache uses so it finds the correct python version. But i donot have multiple versions of python installed. Can anybody give some insight to what can be the problem and hw to reach to the solution ?? Thanks in Advance Boney From pecora at anvil.nrl.navy.mil Wed Nov 29 15:37:10 2006 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Wed, 29 Nov 2006 15:37:10 -0500 Subject: Good script editor for Python on Mac OS 10.3 References: <1164830360.213197.182560@l12g2000cwl.googlegroups.com> Message-ID: In article <1164830360.213197.182560 at l12g2000cwl.googlegroups.com>, "Scott_Davies" wrote: > Hi, > > I have an old Mac with OS X Panther installed. I also have the Python > language download file, but I haven't got a text/script editor to use > for it. Does anyone have a recommendation for a good Python text > editor in OS 10.3? > > Thanks, > > Scott D. > Try TextWrangler. It's free. I use it's big brother BBEdit and like it. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From stefan.behnel-n05pAM at web.de Thu Nov 23 08:35:42 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 23 Nov 2006 14:35:42 +0100 Subject: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]? In-Reply-To: References: Message-ID: <4565A3AE.4030301@web.de> Tor Erik Soenvisen wrote: > (len(['']) is 1) == (len(['']) == 1) => True >>> len(['']) 1 >>> len(['']) is 1 True >>> len(['']) == 1 True >>> True == True True >>> (len(['']) is 1) == (len(['']) == 1) True What did you expect? Stefan From __peter__ at web.de Sun Nov 5 11:50:13 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 05 Nov 2006 17:50:13 +0100 Subject: string to list of numbers conversion References: <1162730071.953080.284980@i42g2000cwa.googlegroups.com> <1162733359.612568.149870@f16g2000cwb.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > This recipe fails when negative numbers are used. > > safe_eval('(12, -12)') > *** Unsafe_Source_Error: Line 1. Unsupported source construct: > compiler.ast.UnarySub > > But, I think it could be easily fixed for somebody who understands the > script. I think that somebody could be you. > Can somebody help. Start with class SafeEval(object): # ... def visitUnarySub(self, node, **kw): return -node.expr.value and then add some error handling. Peter From nszabolcs at gmail.com Wed Nov 22 04:54:41 2006 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 22 Nov 2006 01:54:41 -0800 Subject: gopherlib deprecated in 2.5 Message-ID: <1164189280.934651.290790@m7g2000cwm.googlegroups.com> I've just seen that gopherlib is deprecated in python 2.5 http://docs.python.org/lib/module-gopherlib.html we still use this protocol (though there are only few working gopher servers are left on the net) My friend just wrote a standard compliant gopher server (pygopherd had some problems oslt) and it's much better for hierarchycal content sharing than the http (which is overrated and misused in this respect). So i don't really understand why would one remove it from python. It's a friendly, tiny, simple, standard protocol. what is the opinion of the comp.lang.python crowd? From chrispatton at gmail.com Wed Nov 1 02:03:50 2006 From: chrispatton at gmail.com (Chris) Date: 31 Oct 2006 23:03:50 -0800 Subject: .pyc's In-Reply-To: <1162355223.200685.308760@m73g2000cwd.googlegroups.com> References: <1162354879.039642.195690@k70g2000cwa.googlegroups.com> <1162355223.200685.308760@m73g2000cwd.googlegroups.com> Message-ID: <1162364630.841356.10200@e3g2000cwe.googlegroups.com> thanks marijuanated at gmail.com wrote: > You can try decompyle > > http://packages.debian.org/unstable/python/decompyle > > It works only until python version 2.3 though From timr at probo.com Fri Nov 3 01:53:26 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 03 Nov 2006 06:53:26 GMT Subject: urllib2: HTTP Version not supported References: <1162471925.780264.315870@f16g2000cwb.googlegroups.com> Message-ID: "Nirnimesh" wrote: > >I'm using urllib2 module to fetch a URL from a server which understands >HTTP/1.1 only (no HTTP/1.0). > >urllib2.urlopen() results in "urllib2.HTTPError: HTTP Error 505: HTTP >Version not supported". > >How do I force urllib2 to use HTTP v1.1? Are you passing httplib.HTTPConnection as the connection handler? If you use httplib.HTTP instead, it should create a 1.0 request. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From luismg at gmx.net Wed Nov 15 00:30:20 2006 From: luismg at gmx.net (=?iso-8859-1?Q?Luis_M._Gonz=E1lez?=) Date: Wed, 15 Nov 2006 02:30:20 -0300 Subject: Python v PHP: fair comparison? References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> <1163566115.10270.5.camel@enterprise.local.lan> Message-ID: <001701c70877$27a0f9a0$6e00a8c0@averatecdda041> >> Yes, php is only for web. > > Absolutely false. Most of my standalone, command-line scripts for > manipulating my unix users in LDAP are written in PHP, although we're > rewriting them in python. > > Although I can't think of a single app written in php that's not web- > based (other than standalone scripts I have written), there are up-to- > date php bindings for GTK: http://gtk.php.net/ > > Michael Fair enough, this has been possible due to the enormous popularity of php. You can also hit a nail with your shoe instead of using a hammer, and if you try hard you may even succeed. You can also digg a a grave with a spoon instead of a shovel, and after a couple of days you'll be finished. You may be able to use php to create a stand alone app, but php was created with the solely purpose of being a tool for creating dynamic web sites. And you have to admit that using php for a non-web app is like trying to fit a a square into a round hole. Php is no more than a simplified C-ish language, dynamically typed with a lot of functions aimed at web tasks. Without these built-in functions, there's little you can do with it in your web apps. On the otehr hand, you don't need a thousand built-in functions in python for achieving every single task on a web site. You just write them, often with just a couple of lines, because the language is that flexible an consice. You don't have to remember each and every function for every task, this is ridiculuous. I think that even as a general purpose language, python is still much more adecuate, fast, fun and flexible than php for building web apps. Luis From ptmcg at austin.rr._bogus_.com Thu Nov 30 09:27:05 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 30 Nov 2006 14:27:05 GMT Subject: More elegant to get a name: o.__class__.__name__ References: Message-ID: "alf" wrote in message news:z7mdnTF4I_wfefPYnZ2dnUVZ_rCdnZ2d at comcast.com... > Hi, > is there a more elegant way to get o.__class__.__name__. For instance I > would imagine name(o). > > -- > alf >>> name = lambda o : o.__class__.__name__ >>> name(1) 'int' Go for it! -- Paul From draghuram at gmail.com Fri Nov 10 10:20:24 2006 From: draghuram at gmail.com (draghuram at gmail.com) Date: 10 Nov 2006 07:20:24 -0800 Subject: Newb: installing Jython on Windows XP ... References: <1163095323.668867.58320@i42g2000cwa.googlegroups.com> Message-ID: <1163172024.453732.227340@k70g2000cwa.googlegroups.com> I haven't installed on cygwin or windows XP myself but you should be using "java jython-21". Note that there are two class files "jython-21.class" and "jython_21.class". Also make sure that the CLASSPATH includes the directory that has these two class files. Raghu. donkeyboy wrote: > All, > > I'm having issues installing Jython on Windows XP. I've looked on the > web and this newsgroup but to no avail. Any suggestions? The shell > listing is below: > > NB I've got Cygwin installed, hence the Unix 'ls' on a Windows box > > C:\>cd Jython > > C:\Jython>ls > jython_21.class > > C:\Jython>ls "c:\Program Files\Java\jdk1.5.0_09\bin\java.exe" > c:\Program Files\Java\jdk1.5.0_09\bin\java.exe > > C:\Jython>"c:\Program Files\Java\jdk1.5.0_09\bin\java.exe" jython_21 > Exception in thread "main" java.lang.NoClassDefFoundError: jython_21 > > C:\Jython>"c:\Program Files\Java\jdk1.5.0_09\bin\java.exe" jython-21 > Exception in thread "main" java.lang.NoClassDefFoundError: jython-21 > > Any help would be of great use!!! From daigno at gmail.com Tue Nov 14 23:03:22 2006 From: daigno at gmail.com (=?ISO-8859-1?Q?=C9ric_Daigneault?=) Date: Tue, 14 Nov 2006 23:03:22 -0500 Subject: Python development time is faster. Message-ID: <455A918A.1090208@gmail.com> "Chris Brat" writes: > I've seen a few posts, columns and articles which state that one of the > advantages of Python is that code can be developed x times faster than > languages such as <>. > > Does anyone have any comments on that statement from personal > experience? Well ... Asking this question here is kinna like asking a car dealer if the pontiac in the parking is any good ... :-P > How is this comparison measured? This is hard to measure objectively as there are a LOT of factors to take into account. >From personal experience I found a palpable difference in development speed in favor of Python. My previous experiences were with C++, Java, C and some other specialized languages such as SQL and the occasional Brainfuck to show students that readability can be a useful concept in a language. Other than a few irritants that knowledge and enlightenment quickly iron out the hardest part was to rid myself of the blinkers and shackles that years of Java-C++ enslavement brought on me. Also... >Harry George wrote : > a) Once you get the hang of the language (a weekend?), you can > write without reference to the manuals. Tho a printed quick reference card nearby is a major time saver. I found this one to be useful http://www.limsi.fr/Individu/pointal/python/pqrc/ >Harry George wrote : > Or if you do reference, it > is a quick lookup. No struggling to figure out how to code > something. Or to decypher what a line of code actually does. This is generally true but see below... >Harry George wrote : >c) Peer code reviews are easy -- both you and the reviewers can > understand the code's intent at a glance. Python is completely open and dynamic in nature, this leaves you, the programmer, a *lot* of space for creativity. However this much space in the wrong hands will picasso listings that can be very cryptic and could be very hard to maintain. This being said.... after a bit of experience in programming, design patterns and other marvels of the modern brains, doing bad code in python requires a conscious effort to do. The bright side is that it gives all the justification to reviewers to smack the offenders on the head with a hardcover copy of the GoF. Anyways, my 2 cents ?ric :D. ---- With great power comes great responsibility... From chris.cavalaria at free.fr Thu Nov 9 12:33:18 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 09 Nov 2006 18:33:18 +0100 Subject: How to choose the right GUI toolkit ? In-Reply-To: <1163092380.301382.113470@m7g2000cwm.googlegroups.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163092380.301382.113470@m7g2000cwm.googlegroups.com> Message-ID: <45536639$0$23587$426a34cc@news.free.fr> Dan Lenski a ?crit : > Nick and John S., thank you for the tip on wxPython! I'll look into it > for my next project. I too would avoid Qt, not because of the GPL but > simply because I don't use KDE under Linux and because Qt is not well > supported under Cygwin or on native Windows. Qt is very well supported under Windows! Avoid spreading lies please ;) ( and I must admit one of the reasons I avoid wx if possible, is because I don't use Gnome under Linux and the look and feel of wx applications is really horrible under KDE ) From humitos at gmail.com Tue Nov 21 10:17:30 2006 From: humitos at gmail.com (Manuel Kaufmann) Date: Tue, 21 Nov 2006 12:17:30 -0300 Subject: Parsing/Splitting Line In-Reply-To: <1164088789.316244.124340@b28g2000cwb.googlegroups.com> References: <1164088789.316244.124340@b28g2000cwb.googlegroups.com> Message-ID: <200611211217.30894.humitos@gmail.com> El Martes, 21 de Noviembre de 2006 02:59, acatejr at gmail.com escribi?: > I have a text file and each line is a list of values. The values are > not delimited, but every four characters is a value. How do I get > python to split this kind of data? Thanks. You can define a function very easy to make it. For example you can do: # split-line in 'n' characters import sys def splitLine(line, n): """split line in 'n' characters""" x = 0 y = 0 while line >= n: y = x + n if line[x:y] == '': break yield line[x:y] x += n if __name__ == '__main__': # i get the line-split from the command line # but you can get it from a file for x in splitLine(sys.argv[1], int(sys.argv[2])): print x -- Kaufmann Manuel From odalrick at hotmail.com Thu Nov 2 07:11:36 2006 From: odalrick at hotmail.com (Odalrick) Date: 2 Nov 2006 04:11:36 -0800 Subject: Image creation Message-ID: <1162469496.224218.127540@k70g2000cwa.googlegroups.com> I need to generate wx.Bitmap with a hole in them, i.e. the whole bitmap is one colour, greyish with alpha = 255*.6, except for one rectangle that has alpha = 0 . Currently I'm doing this with PIL, thus: def _init_mask( self ): mask = Image.new( 'RGBA', self.size, color=options['mask_colour'] ) draw = ImageDraw.Draw( mask ) draw.rectangle( self.clip_area.box, fill=( 255, 255, 255, 0) ) self._mask = pilToBitmap( mask, alpha=True ) Obviously this is inefficient, but I couldn't find any way to give alpha values with wxPython's image objects and premature optimization etcetera... Well, now the program works, but is a bit sluggish so I'm asking if anyone can give me some pointers to speeding this up. /Odalrick From rrr at ronadam.com Fri Nov 10 14:01:06 2006 From: rrr at ronadam.com (Ron Adam) Date: Fri, 10 Nov 2006 13:01:06 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: <4554AAB4.10002@hobbshouse.org> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> Message-ID: Michael Hobbs wrote: > The same problem that is solved by not having to type parens around the > 'if' conditional, a la C and its derivatives. That is, it's unnecessary > typing to no good advantage, IMHO. I was coding in Ruby for several > months and got very comfortable with just typing the if conditional and > hitting return, without any extra syntax. When I came back to Python, I > found that I felt annoyed every time I typed the colon, since it > obviously isn't required. The FAQ says that the colon increases > readability, but I'm skeptical. The indentation seems to provide more > than enough of a visual clue as to where the if conditional ends. I'm not sure why '\'s are required to do multi-line before the colon. Possibly because if multi-line conditional expressions are the norm, dropping a colon could result in valid (but incorrect) code instead of an error? The faq also pointed out a technical reason for requiring the colon. It makes the underlying parser much easier to write and maintain. This shouldn't be taken to lightly in my opinion, because a simpler easer to maintain and more reliable python parser means development time can be spent improving the language in other areas instead of fixing parsing problems every time a new feature is added that might be used in a conditional expression. Cheers, Ron From Norbert.Klamann at projecthome.de Thu Nov 30 11:26:22 2006 From: Norbert.Klamann at projecthome.de (Norbert) Date: 30 Nov 2006 08:26:22 -0800 Subject: EasyInstall under Windows - strange behaviour Message-ID: <1164903982.201944.46380@l39g2000cwd.googlegroups.com> Hello all, i try to install ZSI under python 2.5 and windows 2000. I Downloaded the egg and tried the following c:\Python25\Scripts>easy_install.exe c:\download\ZSI-2.0_rc3-py2.5.egg The result is that pythonwin pops up and shows the file : c:\Python25\Scripts\easy_install-script.py : ---------------------------- !C:\Python25\Lib\site-packages\pythonwin\Pythonwin.exe # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==0.6c3','console_scripts','easy_install' __requires__ = 'setuptools==0.6c3' import sys from pkg_resources import load_entry_point sys.exit( load_entry_point('setuptools==0.6c3', 'console_scripts', 'easy_install')() ) ---------------------------- What is going on here ? I presume that there are some trivial things I don't understand, can someone provide apointer or hint ? Thank you for your time ! Norbert From hg at nospam.com Fri Nov 24 12:26:59 2006 From: hg at nospam.com (hg) Date: Fri, 24 Nov 2006 11:26:59 -0600 Subject: Active State and Komodo... In-Reply-To: References: <1164380976.218515.107780@m7g2000cwm.googlegroups.com> Message-ID: Steve Thompson wrote: > On Fri, 24 Nov 2006 07:09:36 -0800, BartlebyScrivener wrote: > >> Steve Thompson wrote: >>> I was wondering the differnced there were betwee Active State's python and >>> the open source version of python. >> The biggest difference at the moment is that ActiveState is still using >> Python 2.4.3 in their distribution. They should be coming out with 2.5 >> soon. >> >> Sounds like you are running Suse? So you already have some version of >> Python, right? You can search this group at comp.lang.python on Google >> Groups--try "python versions linux"--or something like that--but the >> issue you need to watch out for is running two different versions on >> Linux. >> >> Long and short, you don't want to uninstall the version of Python that >> came with your Suse, because other programs on your machine probably >> use that particular version. It's easy to install an ADDITIONAL >> distribution of Python and run it separately, but again. Search the >> list >> for how to do that, and how to run them separately once you do. >> >> I'm just moving to Linux myself, so can't provide the expertise. Unless >> there is some killer feature of 2.5 you need, I would just use the >> Python that came with your Suse. >> >> rd > > Thanks BartlebyScrivener, but are there any other IDE's that are better, > in your opinion, than Eric version 3. I'm using gnome and eric is built > for KDE. I don't care it there open source or Id I have tp puchase one. > > Thanks again, > > Steve I like Eclipse/Pydev better hg From deets at nospam.web.de Wed Nov 1 10:45:13 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 01 Nov 2006 16:45:13 +0100 Subject: Remote Objects via CGI? References: <1162388371.898076.267400@e64g2000cwd.googlegroups.com> Message-ID: <4qrto9FnvnaqU1@uni-berlin.de> kpd wrote: > Three are lots of good looking remote-object implementations for Python > such as Pyro, Rpyc, and PyInvoke. All of these require a deamon > running to serve the remote objects. > > Has anyone seen a method of doing this using CGI or FastCGI instead of > a deamon? I'm not worried about performance for this application, but > I do have constraints on long-running processes. This is pretty much a contradiction to what pyro (the others I don't know, but I bet they are similar) does: serve requests from in-memory living stateful objects. CGI on the other hand will spawn a new process for each request, discarding quite a few aspects. You'd have to re-instantiate the serving objects for each request, if you want to keep the statefulness, you have to persist state between requests and ensure there is some session state communicated. All in all, it can't be done so easily as by only adapting an existing RPC-solution, but you rather should roll out your own. Or stick with what is available, like XMLRPC Diez From mail at microcorp.co.za Fri Nov 17 08:57:04 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 17 Nov 2006 15:57:04 +0200 Subject: Secure Python References: <455c1665@quokka.wn.com.au><455c4d9b@quokka.wn.com.au> Message-ID: <001501c70a50$440b4840$03000080@hendrik> "Stephan Kuhagen" wrote: > The problem with linux kernel limits are, that they won't work really good > on MacOSX and Windows... OTOH the idea is the right one, but the effect can > be achieved inside of Python. Since Python does byte compile the code and > the interpreter evaluates each byte code token in one evaluation step. The > interpreter could be extended for such usecases to count and limit the > number of evaluation steps allowed for untrusted script or methods in > untrusted script as well as to limit the recursion depth or memory to be > allocated. All those limits are managed by the interpreter for script code > and hence can be limited for untrusted code by the interpreter. This also > does not really make DoS impossible (what about C extensions? - maybe > restricting "import"?). - As I said before in this thread, making a sandbox > really secure is a hard job, and may need some serious changes in the > Python interpreter, but AFAIK from Tcl, it is possible - and would be nice > to have. I seem to recall previous discussion on this group about a thing called the bastion module, and that it was deprecated. Not sure if it has any relevance. - Hendrik From notejam at sbcglobal.net Thu Nov 23 14:36:16 2006 From: notejam at sbcglobal.net (notejam) Date: 23 Nov 2006 11:36:16 -0800 Subject: Python 2.5 idle and print command How do I suppress a line feed? Message-ID: <1164310576.767673.297470@h54g2000cwb.googlegroups.com> Hi, I am having a problem with print statements always cause a line feed. I need to print a line of text, then the next print statement will start printing where the last one stopped rather than drop down a line. In basic we can do this with print "texst"; followed by next command print "text2" So how do I do that in python? From steve at REMOVE.THIS.cybersource.com.au Mon Nov 6 06:00:28 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 06 Nov 2006 22:00:28 +1100 Subject: forwarding *arg parameter References: <6pn3h.125$7b6.98@read3.inet.fi> <2Fp3h.195$7b6.100@read3.inet.fi> Message-ID: On Sun, 05 Nov 2006 19:35:58 +0000, Tuomas wrote: > Thanks. My solution became: > > >>> def flattern(arg): > ... result = [] > ... for item in arg: > ... if isinstance(item, (list, tuple)): > ... result.extend(flattern(item)) > ... else: > ... result.append(item) > ... return tuple(result) > ... > >>> def g(*arg): > ... arg = flattern(arg) > ... return arg > ... > >>> def f(*arg): > ... return g(arg) > ... > >>> f('foo', 'bar') > ('foo', 'bar') That's the most complicated do-nothing function I've ever seen. Here is a shorter version: def shortf(*args): return args >>> f('foo', 'bar') ('foo', 'bar') >>> shortf('foo', 'bar') ('foo', 'bar') >>> f(1,2,3,4) (1, 2, 3, 4) >>> shortf(1,2,3,4) (1, 2, 3, 4) >>> f({}, None, 1, -1.2, "hello world") ({}, None, 1, -1.2, 'hello world') >>> shortf({}, None, 1, -1.2, "hello world") ({}, None, 1, -1.2, 'hello world') Actually, they aren't *quite* identical: your function rips lists apart, which is probably not a good idea. >>> f("foo", [1,2,3], None) # three arguments turns into five ('foo', 1, 2, 3, None) >>> shortf("foo", [1,2,3], None) # three arguments stays three ('foo', [1, 2, 3], None) I still don't understand why you are doing this. Can we have an example of why you think you need to do this? -- Steven. From deets at nospam.web.de Thu Nov 30 18:14:22 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 01 Dec 2006 00:14:22 +0100 Subject: Is there a reason not to do this? In-Reply-To: References: Message-ID: <4t96ujF134nv7U1@mid.uni-berlin.de> Ron Garret schrieb: > One of the things I find annoying about Python is that when you make a > change to a method definition that change is not reflected in existing > instances of a class (because you're really defining a new class when > you reload a class definition, not actually redefining it). So I came > up with this programming style: > > def defmethod(cls): > return lambda (func): type.__setattr__(cls, func.func_name, func) > > class c1(object): pass > > @defmethod(c1) > def m1(self, x): ... > > > Now if you redefine m1, existing instances of c1 will see the change. > > My question is: is there a reason not to do this? Does it screw > something up behind the scenes? Is it unpythonic? Why isn't this > standard operating procedure? What are you doing that needs this permanent redefinition? I like the repl, yet usually - especially when dealing with classes - I write a text file containing code. So, i just run that on a command line again, if I made some changes, recreating whatever objects I want again. Even if I'd not do that, but used a long-running interpreter inside an IDE (which is what I presume you are doing) - why do you _care_ about the old objects the first place? I mean, you obviously changed the classes for a reason. So, you are not being productive here, but still programming. Which means that you don't _have_ to care about old, unchanged objects too much. But in the end - it's your code. It will run slower, it looks kinda weird as someone who's reading it has to know what it is for, but if it suits your needs - do it. Diez From paddy3118 at netscape.net Sun Nov 19 01:50:35 2006 From: paddy3118 at netscape.net (Paddy) Date: 18 Nov 2006 22:50:35 -0800 Subject: basic python questions In-Reply-To: <1163918698.063535.209970@k70g2000cwa.googlegroups.com> References: <1163829271.660193.70450@j44g2000cwa.googlegroups.com> <1163868656.416276.277310@m7g2000cwm.googlegroups.com> <4s8u91Fumc9aU1@mid.uni-berlin.de> <1163917049.387309.150740@e3g2000cwe.googlegroups.com> <1163918698.063535.209970@k70g2000cwa.googlegroups.com> Message-ID: <1163919035.448029.242580@b28g2000cwb.googlegroups.com> John Machin wrote: > [Aside] How are you going to explain all this to your instructor, who > may be reading all this right now? > The instructor should be proud! He has managed to do his very first post to a this newsgroup, about a homework question, and do it in the right way. that is no mean feat. - Paddy. From robert.kern at gmail.com Mon Nov 6 15:25:54 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 06 Nov 2006 14:25:54 -0600 Subject: building python with utf-8 default encoding? In-Reply-To: <1162841363.747050.79790@b28g2000cwb.googlegroups.com> References: <1162841363.747050.79790@b28g2000cwb.googlegroups.com> Message-ID: metaperl.etc at gmail.com wrote: > I am playing around with OpenSwarm and was shocked to see that I cannot > build Python with default encoding of utf-8 by passing a flag to > configure... did I miss the option for doing so? No. The default encoding (the return value of sys.getdefaultencoding()) should alway be 'ascii'. Otherwise, programs written on one machine will not run on other machines. -- 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 bjobrien62 at gmail.com Wed Nov 1 15:20:36 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 1 Nov 2006 12:20:36 -0800 Subject: scared about refrences... In-Reply-To: <4547d0d7$0$7246$426a34cc@news.free.fr> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162251429.386255.289620@e3g2000cwe.googlegroups.com> <4547d0d7$0$7246$426a34cc@news.free.fr> Message-ID: <1162412436.595926.66940@i42g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > Nick Vatamaniuc a ?crit : > (snip) > > In Python all the primitives are copied and all other entities are > > references. > > Plain wrong. There's no "primitives" (ie : primitive data types) in > Python, only objects. And they all get passed the same way. so.. def fn(x): x = x + 1 print x a = 2 fn(a) fn(2) Wouldn't you say that this is being passed by value rather than by refrence? From python at greyskies.org Fri Nov 10 16:31:54 2006 From: python at greyskies.org (Melissa Evans) Date: Fri, 10 Nov 2006 16:31:54 -0500 (EST) Subject: Python 2.5 Core Dump on Solaris 8 Message-ID: <20061110162513.T47830@everseek.com> Hi. I'm new to Python. :) I've modified grappy.py, http://www.stacken.kth.se/~mattiasa/projects/grappy/, a postfix policy daemon for greylisting. to use LDAP as a backend instead of SQL (with python-ldap.) The daemon runs fine when testing but when I put it under load it core dumps quickly. What little analysis I know how to do shows similar information every time. Any advice on where to go from here? Thanks! Melissa Python 2.5 on Solaris 8: truss: write(1, " g r e y l i s t e d : ".., 82) = 82 Action:defer_if_permit Temporary failure write(1, " A c t i o n : d e f e r".., 41) = 41 Incurred fault #5, FLTACCESS %pc = 0xFF142794 siginfo: SIGBUS BUS_ADRALN addr=0x0000000F Received signal #10, SIGBUS [default] siginfo: SIGBUS BUS_ADRALN addr=0x0000000F *** process killed *** pflags: core './core' of 12227: python grappy-ldap.py data model = _ILP32 flags = PR_RLC flttrace = 0xfffffbff sigtrace = 0xfffffeff 0xffffffff entryset = 0x00000401 0x04000000 0x00000000 0x00000028 0x80000000 0x00000000 0x00000000 0x00000000 exitset = 0xfffffffe 0xffffffff 0xffffffff 0xffffffd7 0x7fffffff 0xffffffff 0xffffffff 0xffffffff /16: flags = PR_PCINVAL sigmask = 0xffffbefc,0x00001fff cursig = SIGBUS /17: flags = PR_STOPPED why = PR_SUSPENDED /18: flags = PR_STOPPED why = PR_SUSPENDED /19: flags = PR_STOPPED why = PR_SUSPENDED /20: flags = PR_STOPPED why = PR_SUSPENDED /21: flags = PR_STOPPED why = PR_SUSPENDED /1: flags = PR_STOPPED why = PR_SUSPENDED /2: flags = PR_STOPPED|PR_ASLWP why = PR_SUSPENDED sigmask = 0xffbffeff,0x00001fff /3: flags = PR_STOPPED why = PR_SUSPENDED /4: flags = PR_STOPPED why = PR_SUSPENDED /5: flags = PR_STOPPED why = PR_SUSPENDED /6: flags = PR_STOPPED why = PR_SUSPENDED /7: flags = PR_STOPPED why = PR_SUSPENDED /8: flags = PR_STOPPED why = PR_SUSPENDED /9: flags = PR_STOPPED why = PR_SUSPENDED /10: flags = PR_STOPPED why = PR_SUSPENDED /11: flags = PR_STOPPED why = PR_SUSPENDED /12: flags = PR_STOPPED why = PR_SUSPENDED /13: flags = PR_STOPPED why = PR_SUSPENDED /14: flags = PR_STOPPED why = PR_SUSPENDED /15: flags = PR_STOPPED why = PR_SUSPENDED pstack for the suspicious thread: core './core' of 12227: python grappy-ldap.py ----------------- lwp# 16 / thread# 13 -------------------- ff142794 t_delete (ffffffff, 15df78, fffffffd, 1590f0, 3c4cf0, 4e80) + c ff14240c realfree (ffffffff, ff1c2858, ff1bc008, 1590f0, 4e83, 1590f8) + d0 ff142cb0 cleanfree (0, ff1bc008, ff1c27cc, ff1c284c, ff1c281c, 0) + 58 ff141de4 _malloc_unlocked (10, 0, ff1bc008, 10, 1, 0) + f0 ff141fec realloc (ff1c0608, 10, ff1bc008, 4cd80, 10, 0) + 5c 00040278 app1 (26c788, 264610, 1292ec, 0, 25ddd0, 25dddc) + a4 00044324 listappend (26c788, 264610, 1291c4, 8, ff1bfc78, 106418) + 8 0008f1f8 call_function (fe1086a0, 1, 8cc30, 4cd80, 6, 15c45c) + 594 0008cc38 PyEval_EvalFrameEx (2c9668, 1, 0, 2c9668, 1, 1b00f0) + 2be0 0008f73c fast_function (1daaf0, 3d7240, 2, 2c9668, 1b00f0, 2639c0) + c4 0008f5ec call_function (fe108868, 2, 8cc30, 4cd80, 5, 21191c) + 988 0008cc38 PyEval_EvalFrameEx (3d70e8, 1, 0, 3d70e8, 1, 1b00f0) + 2be0 0008f73c fast_function (268c30, 2c8dc4, 1, 3d70e8, 1b00f0, 1b00f0) + c4 0008f5ec call_function (fe108a30, 1, 8cc30, 0, 4, 156ac4) + 988 0008cc38 PyEval_EvalFrameEx (2c8c78, 0, 0, 2c8c78, 1, 1b00f0) + 2be0 0008e03c PyEval_EvalCodeEx (1d4a88, 1cc4b0, 0, 2639cc, 4, 0) + 838 000e2010 function_call (1e0130, 2639c0, 0, e1ed0, 146a98, 14c8e4) + 140 00025c28 PyObject_Call (1e0130, 2639c0, 0, 2639dc, 3, 2639c0) + 20 0002e2ac instancemethod_call (1e0130, 2639c0, 0, 2e09c, 1249f8, 26a9ad) + 210 00025c28 PyObject_Call (26c3a0, 269a58, 0, e2730, 2, 156a5c) + 20 0008ec2c PyEval_CallObjectWithKeywords (26c3a0, 269a58, 0, 332420, 1, 1b00f0) + f4 000290a4 PyInstance_New (269580, 269a58, 0, 28f88, 12462c, 14c8e4) + 11c 00025c28 PyObject_Call (2632d0, 269a58, 0, 0, 269a58, 269a64) + 20 00091ba0 do_call (2632d0, fe1091a0, ffffffff, 0, 26976c, 269760) + 94 0008f604 call_function (fe1091a0, 3, 8cc30, 4, 3, 265754) + 9a0 0008cc38 PyEval_EvalFrameEx (330f98, 3, 0, 330f98, 1, 1b00f0) + 2be0 0008f73c fast_function (1da1b0, 332570, 3, 330f98, 1b00f0, 332108) + c4 0008f5ec call_function (fe109368, 3, 8cc30, 0, 2, 156a5c) + 988 0008cc38 PyEval_EvalFrameEx (332420, 2, 0, 332420, 1, 1b00f0) + 2be0 0008e03c PyEval_EvalCodeEx (1d4728, 1cc4b0, 0, 26976c, 3, 2c0510) + 838 000e2010 function_call (1e00b0, 269760, 26ddb0, e1ed0, 146a98, 14c8e4) + 140 00025c28 PyObject_Call (1e00b0, 269760, 26ddb0, 0, 26976c, 269760) + 20 0008fe8c ext_do_call (1e00b0, fe109604, 3, ffffffff, 0, 23d4b4) + 3ec 0008cd30 PyEval_EvalFrameEx (3, 3323d4, 0, 332298, 1, 1b00f0) + 2cd8 0008f73c fast_function (242f30, 3cd2d4, 1, 332298, 1b00f0, 0) + c4 0008f5ec call_function (fe1097d0, 1, 8cc30, 0, 0, 2a79f4) + 988 0008cc38 PyEval_EvalFrameEx (3cd188, 0, 0, 3cd188, 1, 1b00f0) + 2be0 0008e03c PyEval_EvalCodeEx (23bba8, 2398a0, 0, 25dffc, 1, 0) + 838 000e2010 function_call (242f70, 25dff0, 0, e1ed0, 146a98, 14c8e4) + 140 00025c28 PyObject_Call (242f70, 25dff0, 0, ff1c284c, 0, 25dff0) + 20 0002e2ac instancemethod_call (242f70, 25dff0, 0, 2e09c, 1249f8, 0) + 210 00025c28 PyObject_Call (37da08, 150030, 0, 0, 0, 0) + 20 0008ec2c PyEval_CallObjectWithKeywords (37da08, 150030, 0, 0, 0, 0) + f4 000bdcc0 t_bootstrap (2c08e0, ff09d658, 1, 1, ff09c000, 0) + 1c ff08b01c _thread_start (2c08e0, 0, 0, 0, 0, 0) + 40 From dopey483 at gmail.com Thu Nov 2 09:42:06 2006 From: dopey483 at gmail.com (dopey483 at gmail.com) Date: 2 Nov 2006 06:42:06 -0800 Subject: Sanity check on use of dictionaries Message-ID: <1162478526.063884.155320@b28g2000cwb.googlegroups.com> I am manipulating lots of log files (about 500,000 files and about 30Gb in total) to get them into a little SQL db. Part of this process is "normalisation" and creating tables of common data. I am creating dictionaries for these in a simple {value,key} form. In terms of memory and performance what are the reasonable limits for a dictionary with a key and a 16 character string? eg; if I read in one of my tables from disk into a dictionary, what sizing is comfortable? 100,000 entries? 1,000,000 entries? Lookup times and memory requirements are my main worries. (Running Python 2.3.4 on RH Ent, dual-Xeon with 2GB memory) From grflanagan at yahoo.co.uk Sun Nov 5 08:05:50 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 5 Nov 2006 05:05:50 -0800 Subject: finding the list of the matched strings In-Reply-To: <1162731282.327715.49800@f16g2000cwb.googlegroups.com> References: <1162731282.327715.49800@f16g2000cwb.googlegroups.com> Message-ID: <1162731950.686216.84460@m73g2000cwd.googlegroups.com> jm.suresh at no.spam.gmail.com wrote: > Hi, I have a list of strings. And I want to find the subset which > matches a particular regular expression. > > import re > ll = ('a', 'b', 's1', 's2', '3s') > p = re.compile('^s.*') > newList = filter(lambda s: p.match(s), ll) > > I suppose there should be simple function to do this in re module. Is > there any? > #>>> s = ('a', 'b', 's1', 's2', 'c') #>>> import re #>>> regexp = re.compile('^s.*') #>>> filter( regexp.match, s) #('s1', 's2') #>>> Gerard From no-spam at no-spam-no-spam.invalid Fri Nov 3 17:31:53 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 03 Nov 2006 23:31:53 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> Message-ID: Daniel Dittmar wrote: > robert wrote: >> (IPython is only a special "python network terminal" as already said.) > > Sorry, I thought of IronPython, the .NET variant. > >> Does Jython really eliminate the GIL? What happens when different > > Yes. > >> threads alter/read a dict concurrently - the basic operation in >> python, which is usually not protected by locks. Does Jython use a >> dict data type (and other collection types) which lock during _each_ >> access? in case - that may be very expensive. > > True, though Java synchronization has gotten better and better. Still, > Sun introduced non locking hash tables, so it was a problem. It'd be > interesting to know which kind of dict is used in Jython for attribute > access. I hate Jave :-) , but to come to concerns of this thread, the speed. Found not much about. http://mail.zope.org/pipermail/zpt/2002-March/002884.html says Jython to be at least 9x slower. Is this still the gap (and constant locking a big factor in this). IronPython seems to be surprisingly faster than CPython (sometimes): http://www.python.org/pycon/dc2004/papers/9/ But I cannot imagine, that this includes GIL free locking dicts an all ... !? Is numpy/scipy available for Iron/Jython ? >> garbage is collected earliest, when the refcount went to 0. If it ever >> went to 0, no one will ever use such object again. Thus GC should not >> be different at all. > > Since Python 2.?, there's a mark-and-sweep garbage collection in > addition to the reference counting scheme. This was put into Python to > be able to reclaim object cycles. still that only walks on objects which have already zero refcount. Cannot imagine any additional problems with the GIL. robert From pydecker at gmail.com Wed Nov 1 09:31:27 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 1 Nov 2006 09:31:27 -0500 Subject: wxPython TextCtrl - weird scrolling behavior In-Reply-To: <1162385672.853549.19620@h48g2000cwc.googlegroups.com> References: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> <1162238656.661097.75180@f16g2000cwb.googlegroups.com> <1162240822.260735.316040@e64g2000cwd.googlegroups.com> <2yt1h.206$1n3.4433@news.tufts.edu> <1162242161.009063.65140@e64g2000cwd.googlegroups.com> <1162385672.853549.19620@h48g2000cwc.googlegroups.com> Message-ID: On 1 Nov 2006 04:54:32 -0800, abcd wrote: > thanks for the feedback, I am watching the screencasts, which are > helping already. I think I will try out the Dabo GUI tool since it > uses wxPython...and see if I can get the code I need from it. I think you'll be very impressed. Those guys are creating an excellent tool, and I've found that I can create pretty complicated UIs in a very, very short time with the Class Designer. -- # p.d. From ptmcg at austin.rr._bogus_.com Sun Nov 5 16:39:47 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 05 Nov 2006 21:39:47 GMT Subject: Awesome Python Information References: <1162753631.297470.315570@m7g2000cwm.googlegroups.com> Message-ID: "Brandon" wrote in message news:1162753631.297470.315570 at m7g2000cwm.googlegroups.com... > Check out: www.ChezBrandon.com > By which he means, "do NOT waste your time checking out this ridiculous website with absolutely no Python whatever anywhere." (This is the idiot who claims he saved the Congress from some Mossad poison gas attack, or whatever.) -- Paul From bearophileHUGS at lycos.com Tue Nov 21 12:17:41 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 Nov 2006 09:17:41 -0800 Subject: interleaving dictionary values In-Reply-To: <1164119672.455899.292380@e3g2000cwe.googlegroups.com> References: <1164119672.455899.292380@e3g2000cwe.googlegroups.com> Message-ID: <1164129461.808479.300060@b28g2000cwb.googlegroups.com> d = {"a": [1, 2, 3], "b": [4, 5], "c": [7, 8, 9]} # Simple solution: result = [] for l in d.itervalues(): result.extend(l) print result # Alternative: from itertools import chain print list( chain(*d.itervalues()) ) I don't know what's the faster solution, the first one seem more readable and it's probably fast enough. Bye, bearophile From fredrik at pythonware.com Fri Nov 10 15:36:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 10 Nov 2006 21:36:03 +0100 Subject: Py3K idea: why not drop the colon? In-Reply-To: <4rk5giFrerjfU1@mid.individual.net> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> <4rjlkqFrlskqU1@mid.individual.net> <4rk5giFrerjfU1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Marc 'BlackJack' Rintsch wrote: > >> No it doesn't -- look again at the example given above. It's >> legal syntax in Python but doesn't have the semantics implied by >> the example. > > Sorry, I don't understand -- what is the difference between the > example as it is and the implied semantics of it? >>> color = "blue" >>> if color == "red" or "green" or "yellow": ... print color, "is red or green or yellow" ... blue is red or green or yellow From sjmachin at lexicon.net Wed Nov 1 04:51:31 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Nov 2006 01:51:31 -0800 Subject: High level csv reader In-Reply-To: References: <1162361464.706313.221590@e64g2000cwd.googlegroups.com> Message-ID: <1162374690.950645.246650@b28g2000cwb.googlegroups.com> James Stroud wrote: > George Sakkis wrote: > > It occured to me that most times I read a csv file, I'm often doing > > from scratch things like assigning labels to columns, mapping fields to > > the appropriate type, ignoring some fields, changing their order, etc. > > Before I go on and reinvent the wheel, is there a generic high level > > wrapper around csv.reader that does all this ? > > > > Thanks, > > George > > > > There is a csv in the standard library. Though many of us don't mind > answering questions like this, you can get a lot of answers quicker by > (1) looking to see what's in the standard library and (2) using google. > > http://docs.python.org/lib/module-csv.html > > James The OP mentioned "csv.reader". This indicates to me that he *has* read the csv docs (have you?), and is *already* using the csv module. The tasks he says he does often are *not* covered by the standard library. He appears to be asking if there is a higher-level wrapper around the standard library. Please consider reading his question carefully. From jstroud at mbi.ucla.edu Sun Nov 5 08:04:19 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 05 Nov 2006 13:04:19 GMT Subject: Is there a commas-in-between idiom? In-Reply-To: References: Message-ID: Ernesto Garc?a Garc?a wrote: > Hi experts, > > it's very common that I have a list and I want to print it with commas > in between. How do I do this in an easy manner, whithout having the > annoying comma in the end? > > > > list = [1,2,3,4,5,6] > > # the easy way > for element in list: > print element, ',', > > print > > > # this is what I really want. is there some way better? > if (len(list) > 0): > print list[0], > for element in list[1:]: > print ',', element, > > > > Thx, > Ernesto print ",".joint(some_list) Where what you have named "list" is now called "some_list" because it is terribly ill-advised to reassign the name of a built-in type. James From gabor at nekomancer.net Thu Nov 16 19:26:08 2006 From: gabor at nekomancer.net (gabor) Date: Fri, 17 Nov 2006 01:26:08 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: References: Message-ID: <18c54$455d019b$59ad1aca$24364@news.flashnewsgroups.com> Jean-Paul Calderone wrote: > On Fri, 17 Nov 2006 00:31:06 +0100, "\"Martin v. L?wis\"" > wrote: >> gabor schrieb: >>>> All this code will typically work just fine with the current behavior, >>>> so people typically don't see any problem. >>>> >>> >>> i am sorry, but it will not work. actually this is exactly what i did, >>> and it did not work. it dies in the os.path.join call, where file_name >>> is converted into unicode. and python uses 'ascii' as the charset in >>> such cases. but, because listdir already failed to decode the file_name >>> with the filesystem-encoding, it usually also fails when tried with >>> 'ascii'. >> >> Ah, right. So yes, it will typically fail immediately - just as you >> wanted it to do, anyway; the advantage with this failure is that you >> can also find out what specific file name is causing the problem >> (whereas when listdir failed completely, you could not easily find >> out the cause of the failure). >> >> How would you propose listdir should behave? > > Umm, just a wild guess, but how about raising an exception which includes > the name of the file which could not be decoded? > i also recommend this approach. also, raising an exception goes well with the principle of the least surprise imho. gabor From fredrik at pythonware.com Fri Nov 10 15:33:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 10 Nov 2006 21:33:41 +0100 Subject: Py3K idea: why not drop the colon? In-Reply-To: <45538b0d$0$26485$c3e8da3@news.astraweb.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <45538b0d$0$26485$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: >> Anyway, the FAQ answer seems to be a >> weak argument to me. > > I agree. I was expecting something more technical to justify the colon, > not just that it looks better. yeah, the whole idea of treating programming languages as an interface between people and computers is really lame. no wonder nobody's using Python for anything. From michael at doubleserver.com Fri Nov 24 22:01:01 2006 From: michael at doubleserver.com (J. Michael Caine) Date: Fri, 24 Nov 2006 19:01:01 -0800 Subject: namespace curiosity In-Reply-To: <7fN9h.3178$tM1.367@newsread1.news.pas.earthlink.net> References: <7fN9h.3178$tM1.367@newsread1.news.pas.earthlink.net> Message-ID: <200611241901.01883.michael@doubleserver.com> On Friday 24 November 2006 17:45, Dennis Lee Bieber wrote: > About once a week... It's a FAQ entry! Wonderful! Missed that. Thanks for humoring me. Very satisfying explanation, too... but what else is one to expect from Python? :) From fredrik at pythonware.com Mon Nov 13 14:48:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Nov 2006 20:48:49 +0100 Subject: Printing database output in tabular form In-Reply-To: <1163446803.990020.112810@i42g2000cwa.googlegroups.com> References: <1163446803.990020.112810@i42g2000cwa.googlegroups.com> Message-ID: ronrsr wrote: > when I try to print a web table containing output from a database, I am > getting more info than I want- - > > I would like this to print w'o the array('c', arrays instead of strings? what database is this, and how is that column defined ? From sjmachin at lexicon.net Mon Nov 6 15:49:13 2006 From: sjmachin at lexicon.net (John Machin) Date: 6 Nov 2006 12:49:13 -0800 Subject: Unicode/ascii encoding nightmare References: <1162842650.780517.180360@b28g2000cwb.googlegroups.com> Message-ID: <1162846153.137536.116970@b28g2000cwb.googlegroups.com> Thomas W wrote: > I'm getting really annoyed with python in regards to > unicode/ascii-encoding problems. > > The string below is the encoding of the norwegian word "f?dselsdag". > > >>> s = 'f\xc3\x83\xc2\xb8dselsdag' There is no such thing as "*the* encoding" of any given string. > > I stored the string as "f?dselsdag" but somewhere in my code it got > translated into the mess above and I cannot get the original string > back. Somewhere in your code??? Can't you track through your code to see where it is being changed? Failing that, can't you show us your code so that we can help you? I have guessed *what* you got, but *how* you got it boggles the mind: The effect is the same as (decode from latin1 to Unicode, encode as utf8) *TWICE*. That's how you change one byte in the original to *FOUR* bytes in the "mess": | >>> orig = 'f\xf8dselsdag' | >>> orig.decode('latin1').encode('utf8') | 'f\xc3\xb8dselsdag' | >>> orig.decode('latin1').encode('utf8').decode('latin1').encode('utf8') | 'f\xc3\x83\xc2\xb8dselsdag' | >>> > It cannot be printed in the console or written a plain text-file. Incorrect. *Any* string can be printed on the console or written to a file. What you mean is that when you look at the output, it is not what you want. > I've tried to convert it using > > >>> s.encode('iso-8859-1') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: > ordinal not in range(128) encode is an attribute of unicode objects. If applied to a str object, the str object is converted to unicode first using the default codec (typically ascii). s.encode('iso-8859-1') is effectively s.decode('ascii').encode('iso-8859-1'), and s.decode('ascii') fails for the (obvious(?)) reason given. > > >>> s.encode('utf-8') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: > ordinal not in range(128) Same story as for 'iso-8859-1' > > And nothing helps. I cannot remember hacing these problems in earlier > versions of python I would be very surprised if you couldn't reproduce your problem on any 2.n version of Python. > and it's really annoying, even if it's my own fault > somehow, handling of normal characters like this shouldn't cause this > much hassle. Searching google for "codec can't decode byte" and > UnicodeDecodeError etc. produces a bunch of hits so it's obvious I'm > not alone. > > Any hints? 1. Read the Unicode howto: http://www.amk.ca/python/howto/unicode 2. Read the Python documentation on .decode() and .encode() carefully. 3. Show us your code so that we can help you avoid the double conversion to utf8. Tell us what IDE you are using. 4. Tell us what you are trying to achieve. Note that if all you are trying to do is read and write text in Norwegian (or any other language that's representable in iso-8859-1 aka latin1), then you don't have to do anything special at all in your code-- this is the good old "legacy" way of doing things universally in vogue before Unicode was invented! HTH, John From john106henry at hotmail.com Sat Nov 11 15:32:48 2006 From: john106henry at hotmail.com (John Henry) Date: 11 Nov 2006 12:32:48 -0800 Subject: How to choose the right GUI toolkit ? In-Reply-To: <43hal2p6ep7vds2nl55uqil7v7i3guncl2@4ax.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163015347.164393.74110@i42g2000cwa.googlegroups.com> <6ov7l2lb9ip2u5jmd54e2kso1s78fc68bb@4ax.com> <1163139352.206221.213180@m73g2000cwd.googlegroups.com> <1163141290.868726.11330@h48g2000cwc.googlegroups.com> <43hal2p6ep7vds2nl55uqil7v7i3guncl2@4ax.com> Message-ID: <1163277168.079436.65120@e3g2000cwe.googlegroups.com> BTW: I did a search and found the testnotebook example from: http://prdownloads.sourceforge.net/pythoncard/testNotebook.zip?download and tried it out. There is one error in the widget.py that I have to get around. Changed from: canvas.setFillColor('gray') to: try: canvas.setFillColor('gray') except: pass and then ran it. Works! So, yes, you can do Notebook in Python. I believe what they are saying is that Notebook isn't supported fully (yet) in the resourceeditor. Bill Maxwell wrote: > On 9 Nov 2006 22:48:10 -0800, "John Henry" > wrote: > > >Upon closer look, the walkthrough did say: > > > >*************************** > >from PythonCard import model > > > >Change that so it says: > > > >from PythonCard import dialog, model > > > >Save the code. > >*************************** > > > >So, it works. > > > Thanks for looking into it. It sounds like either it has been fixed in > the newer version -- or I didn't do something correctly. It's been a > long time, and I was just going by the notes I made back then. > > > > > > > > > > > > > > > > >John Henry wrote: > >> Bill Maxwell wrote: > >> > On 8 Nov 2006 11:49:07 -0800, "John Henry" > >> > wrote: > >> > > >> > > > >> > >John Salerno wrote: > >> > >> Dan Lenski wrote: > >> > >> > >> > >> > So, is there another toolkit I should be looking at? > >> > >> > >> > >> I highly recommend wxPython. It's very mature, full-featured, and > >> > >> portable, and fairly easy to learn as well. I can't really compare it to > >> > >> other toolkits (not having used any of them, except Tkinter), but it's > >> > >> definitely one of the most popular and well-supported ones out there. > >> > >> > >> > >> http://www.wxpython.org/ > >> > > > >> > >I highly recommend that you try PythonCard (which sits on top of > >> > >wxPython). You can get productive very very quickly. Take a look at: > >> > > > >> > >http://pythoncard.sourceforge.net/walkthrough1.html > >> > > >> > > >> > I took a brief look at PythonCard almost a year ago and got discouraged > >> > by what I found, so I stopped looking at it. I've inserted my notes > >> > from back then, below. Does anybody know if these things have been > >> > fixed in the latest release? > >> > > >> > Bill > >> > > >> > > >> > ===================================================================== > >> > My notes from Fri Dec-23-2005: > >> > > >> > This is a list of gripes I have while trying to learn about PythonCard. > >> > I'm trying to investigate various GUI builders for Python, and > >> > PythonCard looks promising, but a lot of things are getting in the way. > >> > > >> > I installed yesterday, using this installer: > >> > PythonCard-0.8.1.FIXED.win32.exe > >> > > >> > A) The very first example in the tutorial is wrong! > >> > > >> > On this page: http://pythoncard.sourceforge.net/documentation.html > >> > When you follow this link to try something for the very first time: > >> > > >> > Getting Started in PythonCard by Dan Shafer: > >> > http://pythoncard.sourceforge.net/walkthrough1.html > >> > > >> > You quickly see that the minimal.py example doesn't even contain > >> > this line, even though the tutorial refers to it: > >> > > >> > >> I am not sure which one you are referring to but in the > >> PythonCard\samples\minimal, you will find a minimal.py that says: > >> > >> #!/usr/bin/python > >> > >> """ > >> __version__ = "$Revision: 1.8 $" > >> __date__ = "$Date: 2005/12/17 15:20:02 $" > >> """ > >> > >> from PythonCard import model > >> > >> > >> class Minimal(model.Background): > >> def on_menuFileAbout_select(self, event): > >> pass > >> > >> if __name__ == '__main__': > >> app = model.Application(Minimal) > >> app.MainLoop() > >> > >> > >> > >> > def on_menuFileAbout_select(self, event): > >> > > >> > And, of course, if you replace the word "pass" with this, as > >> > instructed: > >> > > >> > result = dialog.alertDialog(self, 'It works!', 'Showing Off') > >> > > >> > it won't run, because the existing "pass" line isn't inside a def > >> > inside of a class. > >> > > >> > >> No, it didn't work because the author forgot to mention that you have > >> to do a: > >> > >> from PythonCard import model, dialog > >> > >> instead of just: > >> > >> from PythonCard import model > >> > >> I just tried it and it works. > >> > >> > > >> > B) Is the Notebook widget really supported? > >> > > >> > In the installed file "changelog.txt" (gets installed as part of > >> > PythonCard installation), it says: > >> > > >> > "added Notebook component, PageBackground, and testNotebook > >> > sample" > >> > > >> > But, the testNotebook sample is nowhere to be found. > >> > > >> > >> I haven't come across a need to use Notebook and so I can not say for > >> sure. Looking at notebook.py, it appears to be just a simple wrapper > >> on top of the wxWindow notebook. I would encourage you to post a > >> message to the mailing list and ask there. > >> > >> > >> > I looked lots of places, including the main SourceForge web site, > >> > and on the wiki, here: > >> > > >> > http://wiki.wxpython.org/index.cgi/PythonCard > >> > > >> > Both the main website and the wiki seem way out of date, and the > >> > latest dates I could find on both of them are sometime in 2004. > >> > > >> > >> Yes, sometime around 2004, the website updating stopped. Fortunately, > >> development didn't. There are quite a number of new things since then: > >> new resource editor (now call layout Editor, standalone exe creator, > >> and so forth). I even learn that a new sizer handler is in the work. > >> > >> Not saying that there are 10 programmers working 7/24 on it. It *is* > >> an Open Source project nevertheless. Nobody gets paid for doing it. > >> But there are development work going on. > >> > >> > >> > Finally, by following the mailing list archive link on the main > >> > website, I managed to find a reference to the notebook component on the > >> > ASPN site, where some guy named Brian wonders about the same thing as > >> > me, concerning the availability of the notebook component: > >> > > >> > http://aspn.activestate.com/ASPN/Mail/Message/pythoncard/2536825 > >> > > >> > and, that message led me here: > >> > > >> > http://article.gmane.org/gmane.comp.python.pythoncard/1060 > >> > > >> > where Kevin Altis admits that he forgot to include it in the 0.8.1 > >> > release! At least he provides a way to download it separately. But, > >> > gheesh, this is pretty poor for a new user. I was interested in using > >> > the notebook component right away, because I looked at the wxGlade > >> > tutorial before looking at PythonPage, and they use the notebook > >> > component in their example (and I decided I really want to use the > >> > component). > >> > > >> > To add insult to injury, after you download the zip file with the > >> > testNotebook stuff, the readme file says this: > >> > > >> > "Until we have a Notebook integrated into some of the other > >> > samples or tools this will serve as a basic test app, but I don't expect > >> > to include it in releases." > >> > > >> > >> > >> As with all Open Source projects, your mileage differs. PythonCard > >> does what *I* need to get done - and allowed me to get it done in a > >> *hurry*. May be you really need Notebook and may be it's true that > >> Notebook really doesn't work, I don't know. But if you managed to get > >> it working, write it up and get it included. That's what Open Source > >> Projects are all about. > >> > >> > >> > C) Are the websites being maintained? > >> > >> > >> It appears that the maintainer of the web site stopped updating it > >> since late 2004. I don't know why. May be he's been busy. May be he > >> got mad. I don't know. All I know is that I have been very > >> productive with what I need to get done (and earned a happy living with > >> the code I created) and I am very grateful to the people that worked on > >> it - past and present. > >> > >> I am not a "professional programmer" and so I probably can't contribute > >> to the development effort itself. However, I've gotten pretty good in > >> using most of the package (other then Notebook, I admit). So, if you > >> have any specific questions, please post it to the PythonCard list and > >> I'll try to help if I can. > >> > >> Cheers. From jfabiani at yolo.com Wed Nov 22 11:19:42 2006 From: jfabiani at yolo.com (johnf) Date: Wed, 22 Nov 2006 08:19:42 -0800 Subject: Python visual IDE References: <1164188410.516169.171150@f16g2000cwb.googlegroups.com> Message-ID: king kikapu wrote: > > Hi to all, > > i am not sure if this question really belongs here but anyway, here it > goes: I have seen a lot of IDEs for Python, a lot of good stuff but > actually none of them has what, for example, Visual Studio has: a > Visual Editor (with the ability to place controls on forms etc etc), > or RAD > > I know that there is Glade but does anybody knows of some product, or > an ongoing effort to this direction so i can have a look at ? > > Coming from Windows and vs.net world, i think the only missing point > here is the integration of the Pyrthon with a RAD IDE... > > Thanks a lot and i apologize if this isn't the correct place for this > question... > > > Kikapu You might want to check out "dabo" www.dabodev.com. It's only at .7 but it has a GUI designer (uses wxPython). Has a 3 tier design and able to use MySQL, Postgres, FireBird, and soon MSSQL. The project has a ways to go but it's goal is to be similar to windows IDEs such as VFP, VB6 and VS. John From fuzzyman at gmail.com Tue Nov 21 05:51:09 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 21 Nov 2006 02:51:09 -0800 Subject: The Python Papers Edition One In-Reply-To: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> Message-ID: <1164106267.882164.124670@h48g2000cwc.googlegroups.com> tleeuwenburg at gmail.com wrote: > Greetings all, > > Some of you may have noticed the launch of the Python Journal a while > back. Due to artistic differences, the journal has now been re-launched > as The Python Papers. It is available under a Creative Commons License, > something we felt was appropriate given its nature. Many here commented > that this was important to them, and it is important to us also. > > For a fuller description of what we hope the journal to be, I re-create > my inaugural blog posting at the end of this email, or it can be found > online here: http://pythonpapers.cgpublisher.com/diary > > Some of you had a number of specific points to raise, which I can now > answer properly since launching under our own banner. > [snip..] > > 3.) Can I have an HTML version? > A) No, we like it pretty. > Congratulations - it looks very professional. *But*, PDF is an abhorrent format unless you expect people to print it. Your download system almost certainly guarantees that the content won't be indexed by search engines and so is much less likely t obe found by people who will find it interesting and useful. :-) Make sure annnouncements make their way onto PlanetPython (if they're not already..). Fuzzyman http://www.voidspace.org.uk/index2.shtml From timothy at open-networks.net Sat Nov 4 18:12:32 2006 From: timothy at open-networks.net (timmy) Date: Sun, 05 Nov 2006 09:12:32 +1000 Subject: py2exe questions In-Reply-To: References: Message-ID: <454d1dee$1@quokka.wn.com.au> Doug Stell wrote: > I have 2 questions about py2exe or any similar utility. > > 1. Is it possible to create a single Windows executable that does not > blow out to a folder full of files and can be called from scripts > using command line arguments? py2exe can most certainly do this. > > 2. If the above can be done, it is possible to hide parts of the > Python source code from users? These users are software developers, > but we don't want them to see how the code does what it does. > > thanks, doug you can make a single exe in py2exe which would make it harder to disassemble, but there's no such thing in the software world that makes it impossible. From sjmachin at lexicon.net Thu Nov 16 06:26:51 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Nov 2006 03:26:51 -0800 Subject: split CSV fields In-Reply-To: References: <1163674830.440318.246920@f16g2000cwb.googlegroups.com> <1163675506.590469.251910@h48g2000cwc.googlegroups.com> Message-ID: <1163676411.121177.302160@h48g2000cwc.googlegroups.com> Fredrik Lundh wrote: > John Machin wrote: > > > Given Peter Otten's post, looks like > > (1) there's a bug in the "fmtparam" mechanism -- it's ignoring the > > escapechar in my first twiddle, which should give the same result as > > Peter's. > > (2) > > | >>> csv.excel.doublequote > > True > > According to my reading of the docs: > > """ > > doublequote > > Controls how instances of quotechar appearing inside a field should be > > themselves be quoted. When True, the character is doubled. When False, > > the escapechar is used as a prefix to the quotechar. It defaults to > > True. > > """ > > Peter's example should not have worked. > > the documentation also mentions a "quoting" parameter that "controls > when quotes should be generated by the writer and recognised by the > reader.". not sure how that changes things. Hi Fredrik, I read that carefully -- "quoting" appears to have no effect in this situation. > > anyway, it's either unclear documentation or a bug in the code. better > submit a bug report so someone can fix one of them. Tomorrow :-) Cheers, John From cdroulers at hotmail.com Wed Nov 8 22:29:22 2006 From: cdroulers at hotmail.com (Sefyroth) Date: 8 Nov 2006 19:29:22 -0800 Subject: Problem getting a file pathname with tkFileDialog In-Reply-To: References: <1163012468.055428.124690@h48g2000cwc.googlegroups.com> <1163016063.961485.224390@k70g2000cwa.googlegroups.com> Message-ID: <1163042962.854488.296190@b28g2000cwb.googlegroups.com> Thank you!!! I have had problems with other stuff because of this (mainly py2exe!) It did the job! I thank you a lot. Just wondering though, D:/Travaux/5?me session/B51 - Dev. de Syst?mes/Workspace/LMAOSoft/Controleur.py That's my filepath, what is not ASCII in there? ????? Just checked and it's 138 in ascii... Anyway, thanks a lot Christian Tim Daneliuk wrote: > Sefyroth wrote: > > Thanks, > > > > but I get this error when I try this. > > > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in > > position 12: ordinal not in range(128) > > > > I had encountered it with the askdirectory method as well. Is there an > > easy way to bypass this? > > > > Thanks again > > I believe you are running into a directory or file name that has > non-ascii characters in it. Python as shipped is set up to > deal with ascii as its native encoding format. You can change > this by editing the "site.py" file - look in the Lib directory > in your python installation. Look for this code: > > ------------------------------- > def setencoding(): > """Set the string encoding used by the Unicode implementation. The > default is 'ascii', but if you're willing to experiment, you can > change this.""" > encoding = "ascii" # Default value set by _PyUnicode_Init() > if 0: > # Enable to support locale aware default string encodings. > import locale > loc = locale.getdefaultlocale() > if loc[1]: > encoding = loc[1] > ------------------------------- > > > > Change the "if 0:" to "if 1:" and see if that doesn't fix the problem. > > > > -- > ---------------------------------------------------------------------------- > Tim Daneliuk tundra at tundraware.com > PGP Key: http://www.tundraware.com/PGP/ From bignose+hates-spam at benfinney.id.au Wed Nov 1 09:44:25 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 02 Nov 2006 01:44:25 +1100 Subject: best way to check if a file exists? References: <1162383348.925961.231160@h48g2000cwc.googlegroups.com> <1162390455.727684.118970@b28g2000cwb.googlegroups.com> Message-ID: <8764dz5ira.fsf@benfinney.id.au> "wittempj at hotmail.com" writes: > Ben Finney wrote: > > "wittempj at hotmail.com" writes: > > > You could try to read the file, if that fails it doesn't exist: > > > > Except that there are other conditions than "File doesn't exist" > > that can cause an 'open' to fail. > > Ok, true. You can test explicit on non existence as follows, and then > decide to open the file Or you can simply use 'os.path.exists', as has been suggested several times in this thread. -- \ "The way to build large Python applications is to componentize | `\ and loosely-couple the hell out of everything." -- Aahz | _o__) | Ben Finney From claird at lairds.us Thu Nov 30 18:28:25 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 30 Nov 2006 23:28:25 +0000 Subject: Ruby/Python/REXX as a MUCK scripting language References: <2006112418112116807-zobeid@techiecom> <4sr3neF111j0gU1@mid.individual.net> Message-ID: In article , Laurent Pointal wrote: >Fred Bayer a ?crit : >> >> Tony Belding wrote: >>> I'm interested in using an off-the-shelf interpreted language as a >>> user-accessible scripting language for a MUCK. I'm just not sure if I . . . >>> there's the security issue that really worries me. . . I have to be >>> able to limit what the interpreter can execute. I can't have my users >>> running scripts that access the console, access the filesystem or >>> sockets directly, or call libraries or other binaries outside the MUCK. >>> >>> Is this practical? I'm thinking of Ruby or Python for this, if they >>> can meet the requirements. >>> >> >> Don't forget Lua: www.lua.org >> It fulfills your requirements and is easily embedable. >> > >I Agree with F.Bayer, when reading OP post, I immediatly think about Lua. > > > Does Lua have an appropriate security model--a sandbox or such? Fond though I am of Lua, such would be news to me. From __peter__ at web.de Wed Nov 8 14:19:39 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Nov 2006 20:19:39 +0100 Subject: is this the right way to do subclasses? References: <45522074$0$17101$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Ok, back to my so-called "game." I'm just curious if I've implemented > the subclasses properly, because it seems like an awful lot of > repetition with the parameters. And again, if I want to add a new > attribute later, I'd have to change a lot of things. I can't help but > get the feeling that I'm doing something very inefficiently. > class Character(object): > > def __init__(self, name, strength, dexterity, intelligence): > self.name = name > self.health = 10 > self.strength = strength > self.dexterity = dexterity > self.intelligence = intelligence > > > class Fighter(Character): > > def __init__(self, name, strength, dexterity, intelligence): > Character.__init__(self, name, strength, dexterity, intelligence) > self.health += 2 > self.strength += 1 One way to avoid the repetition: class Character(object): def __init__(self, name, strength, dexterity, intelligence): self.name = name self.health = 10 self.strength = strength self.dexterity = dexterity self.intelligence = intelligence self.fix_attributes() class Fighter(Character): def fix_attributes(self): self.health += 2 self.strength += 1 You may need a no-op implementation of fix_attributes() in the Character class. Peter From http Sat Nov 25 04:39:45 2006 From: http (Paul Rubin) Date: 25 Nov 2006 01:39:45 -0800 Subject: The Python Papers Edition One References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <7xodqyn5kd.fsf@ruckus.brouhaha.com> <1164323350.988946.209350@l12g2000cwl.googlegroups.com> <1164340388.885058.264750@l12g2000cwl.googlegroups.com> Message-ID: <7xbqmvn9um.fsf@ruckus.brouhaha.com> "tleeuwenburg at gmail.com" writes: > Your email indicates a possible concern that we are doing something > untoward -- this was not at all intended, nor is it true. Although you might not have intended it, I feel it is still true. You are misappropriating terminology ("free as in freedom") from the free software movement that means a work is licensed in a way that meets some specific criteria, that the license you're using does not meet. From gabrielg_laburando at yahoo.com.ar Thu Nov 30 02:19:01 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Thu, 30 Nov 2006 04:19:01 -0300 Subject: Python Question About Compiling. In-Reply-To: <5b0fce7a0611292240k7c393468u48ffed455ec0feaa@mail.gmail.co m> References: <5b0fce7a0611292057p4d429226v9d3416ac9712e2@mail.gmail.com> <5b0fce7a0611292102g4a345b49h2a6e9c1f51ab4003@mail.gmail.com> <7.0.1.0.0.20061130033226.01fe7b98@yahoo.com.ar> <5b0fce7a0611292240k7c393468u48ffed455ec0feaa@mail.gmail.com> Message-ID: <7.0.1.0.0.20061130041705.04082e68@yahoo.com.ar> At Thursday 30/11/2006 03:40, Scheol Service wrote: >i know this. Is there better directions on how to use it? Have you tried it? What's your actual problem? See http://www.py2exe.org/ -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From 2huggie at gmail.com Sun Nov 26 04:17:51 2006 From: 2huggie at gmail.com (Timothy Wu) Date: Sun, 26 Nov 2006 17:17:51 +0800 Subject: Generator question Message-ID: Hi, Using generator recursively is not doing what I expect: def test_gen(x): yield x x = x - 1 if x != 0: test_gen(x) for item in test_gen(3): print item This gives me a single number 3 and not printing 2 and 1 as I would expect. What is wrong?? Timothy -------------- next part -------------- An HTML attachment was scrubbed... URL: From nick at craig-wood.com Thu Nov 16 01:32:55 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 16 Nov 2006 00:32:55 -0600 Subject: Python-2.5.exe? References: Message-ID: Fredrik Lundh wrote: > Andrew Burton wrote: > > > What Python is best for installing to a USB Drive? I've actually got > > 2.5 on a drive, but I forget which installation package I used. It > > seems to me that it was an EXE file, but I cannot seem to find one of > > those today. > > > > Can the Python-2.5.msi installation files from python.org be installed > > so as not to touch the registry, to make them portable? > > python doesn't depend on the registry settings for normal use, so > you can simply install python as usual, copy python25.dll from > c:\windows\system32 to c:\python25, and then copy (or move) the > entire c:\python25 tree to your USB drive. As well as the above, I find a little .bat file like this to set some paths and start python or your application is helpful, eg @echo off set DEMOHOME=%CD% set PYTHONHOME=%DEMOHOME%\Python24 set PYTHONPATH=%PYTHONHOME%;%DEMOHOME%\Demo\Python set PYTHON=%PYTHONHOME%\python.exe set PYTHONW=%PYTHONHOME%\pythonw.exe set PATH=%PYTHONHOME%;%PATH% start "Demo" "%PYTHONW%" "demo.pyw" -- Nick Craig-Wood -- http://www.craig-wood.com/nick From george.sakkis at gmail.com Sat Nov 11 15:04:21 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 11 Nov 2006 12:04:21 -0800 Subject: handling many default values References: Message-ID: <1163275461.313876.224480@m7g2000cwm.googlegroups.com> Ben Finney wrote: > "Alan Isaac" writes: > > > There are *many* parameters, and the list can change, so I want to > > avoid listing them all in the Param class's __init__ function, using > > the strategy above. > > > > Q1: Is this approach reasonable? > > (This is a newbie question about unforseen hazards.) > > Q2: Is it horrible design to isolate the parameters in a separate class? > > (Comment: currently several classes may rely on (parts of) the same > > parameter set.) > > It's a bad design smell to have functions that accept large numbers of > parameters, many of them optional. Such an interface is difficult to > document, maintain and test. > > You should certainly be examining such code and seeing how much of it > can be implemented instead as functions with small, well-defined > parameter lists. This may mean writing more functions, or more layers > of functions, or more classes, or whatever; but having a result that > uses small, well-defined interfaces is a valuable property. So I guess you prefer the (os.system, os.spawn*, os.popen*, popen2.*, commands.*) kitchen sink than the single versatile subprocess.Popen class, right ? I respectfully disagree, and I'm all for one-class-does-it-all, as long as most parameters are optional and the default values address the most typical/reasonable case. To answer to OP's question, your approach is totally reasonable and well-known; the csv.Dialect class for example is exactly this, a parameter-holding class. George From carsten at uniqsys.com Fri Nov 17 17:20:49 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 17 Nov 2006 17:20:49 -0500 Subject: Decimal() instead of float? In-Reply-To: <1163800304.5107.179.camel@pepper> References: <1163294604.4675.4.camel@pepper> <1163511997.4675.88.camel@pepper> <4559F828.7070704@holdenweb.com> <1163794251.5107.151.camel@pepper> <1163800304.5107.179.camel@pepper> Message-ID: <1163802049.3358.43.camel@dot.uniqsys.com> On Fri, 2006-11-17 at 16:51 -0500, Michael B. Trausch wrote: > On Fri, 2006-11-17 at 21:25 +0100, Fredrik Lundh wrote: > > > Some of the lat/long pairs that I have used seem to come out fine, but > > > some do not. Because the mathmatics used with them involve complex > > > equations when determining distance and the like, any error gets > > > massively compounded before a final result is evident. > > > > sorry, but I don't think you have the slightest idea what you're doing, > > really. > > > > Sure, I do. Let's say that I want to work with the latitude > 33.6907570. In Python, that number can not be stored exactly without > the aid of decimal.Decimal(). > > >>> 33.6907570 > 33.690756999999998 > >>> > > As you can see, it loses accuracy after the 6th decimal place. That's > not good enough: I have 8 numbers that need to be exact, and I am > only getting six. Really? >>> x = 33.6907570 >>> for i in range(7,16): print "%.*f" % (i,x) ... 33.6907570 33.69075700 33.690757000 33.6907570000 33.69075700000 33.690757000000 33.6907570000000 33.69075700000000 33.690756999999998 Looks to me like you're getting, uh, 14 decimal digits, for a total of 16 significant digits. What kinds of operations are you performing that compound this error by seven orders of magnitude? -Carsten From Eric_Dexter at msn.com Wed Nov 22 22:37:14 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 22 Nov 2006 19:37:14 -0800 Subject: The Python Papers Edition One In-Reply-To: <1164244166.988532.261370@l39g2000cwd.googlegroups.com> References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <1164106267.882164.124670@h48g2000cwc.googlegroups.com> <1164156093.359433.315790@e3g2000cwe.googlegroups.com> <1164244166.988532.261370@l39g2000cwd.googlegroups.com> Message-ID: <1164253034.295391.56720@j44g2000cwa.googlegroups.com> The adobe people have online conversion http://www.adobe.com/products/acrobat/access_onlinetools.html google seems to convert them when they end up in the engines http://www.google.com/search?hl=en&q=pdf+to+html has a list of converters http://www.dexrow.com garylinux at gmail.com wrote: > Tell us about it again when it is available as html. We will be glad to > read it. I am sorry but I almost never find a pdf worth the bother of > clicking on it. > Sorry From mgi820 at motorola.com Tue Nov 21 14:37:06 2006 From: mgi820 at motorola.com (Gary Duzan) Date: Tue, 21 Nov 2006 19:37:06 +0000 (UTC) Subject: How good is CORBA? References: Message-ID: In article , Sai Krishna M wrote: >Hi everybody, > >i have been developing web based applications using python+cheetah. > >The numbers are increasing. The applications have many common parts of >code. Though these applications are separate from each other they are >run in the same server. > >I heard about CORBA... but also heard that it has some flaws...like >the programming being very complicated. >Also heard that CORBA is no more used these days... CORBA is good for what it is good for. It does take some time to get up to speed on it, but eventually most of it makes sense. Some of the language mappings, especially C++, can be hard to use safely, but the Python mapping is much easier to use. If you need good performance, multiple language support, multiple OS/hardware platform support, and preferably control both ends of the communication, CORBA may be for you. Check out omniORB for C++ and Python (http://omniorb.sourceforge.net/), and JacORB for Java (http://www.jacorb.org/). Good luck. Gary Duzan Motorola CHS From ronrsr at gmail.com Mon Nov 20 02:36:17 2006 From: ronrsr at gmail.com (ronrsr) Date: 19 Nov 2006 23:36:17 -0800 Subject: Not enough arguments for format string In-Reply-To: References: <1163991320.262638.154950@j44g2000cwa.googlegroups.com> Message-ID: <1164008177.514993.283390@j44g2000cwa.googlegroups.com> thanks. solution 1 worked like a charm. Paul McGuire wrote: > "ronrsr" wrote in message > news:1163991320.262638.154950 at j44g2000cwa.googlegroups.com... > > is the error message I'm getting here, on the long formatted print > > From l.m.aangeenbrug at gmail.com Mon Nov 13 14:49:06 2006 From: l.m.aangeenbrug at gmail.com (lennart) Date: 13 Nov 2006 11:49:06 -0800 Subject: Is python for me? In-Reply-To: References: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> <1163441697.231672.163480@k70g2000cwa.googlegroups.com> Message-ID: <1163447345.986774.289950@h54g2000cwb.googlegroups.com> Carsten Haese schreef: > On Mon, 2006-11-13 at 10:14 -0800, Dan Lenski wrote: > > lennart wrote: > > > So i ask myself is python the language I'm looking for? > > > > Yep! Python is very much a jack-of-all-trades language. > > I'll run the risk of being nitpicky, but the full phrase is "Jack of all > trades, master of none," which doesn't do Python justice. Python is a > master of all trades! > > But I agree with Dan's sentiment, Python is definitely the language > you're looking for. > > -Carsten. Tnx everyone for your response! It's just for me a big step to learn a new language. Not because of the difficulty, but because of the time and so. Later, i remembered that Gimp can also work with python (scripts). So, even for my second wish, there will be somewhere, somehow a way to do it. At least: i use the dutch portal http://python.startpagina.nl/ to start with. Can you advice me a good Python interpreter, or a good startpage (as in Python for dummys)? Lennart From rthorpe at realworldtech.com Fri Nov 3 05:33:24 2006 From: rthorpe at realworldtech.com (Robert Thorpe) Date: 3 Nov 2006 02:33:24 -0800 Subject: Javascript is turning into Python?! In-Reply-To: <7xslh1dmgt.fsf_-_@ruckus.brouhaha.com> References: <7xslh1dmgt.fsf_-_@ruckus.brouhaha.com> Message-ID: <1162550003.984693.208120@f16g2000cwb.googlegroups.com> Paul Rubin wrote: > I hadn't seem this before. New Javascript 1.7 features: > > - Generators > - Iterators > - Array comprehensions > - Destructuring assignment > > Sounds like another language we know. > > http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7 Indeed, this is a consequence of Greenspun's tenth rule, and it's good. It doesn't have much to do with GNU Emacs though. From mike$#at^&nospam!%trauschus Fri Nov 3 21:19:27 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Fri, 03 Nov 2006 21:19:27 -0500 Subject: Converting Microsoft Works databases.... *shudder* In-Reply-To: <1162568409.144421.262160@e3g2000cwe.googlegroups.com> References: <1162568409.144421.262160@e3g2000cwe.googlegroups.com> Message-ID: <0cednc5i_d0yZdbYnZ2dnUVZ_sGdnZ2d@comcast.com> GISDude wrote: > Mike, > I totally forgot that MS Works was out there. Haven't used that one in > about 6 or 7 years. Honestly, your best bet is to convert to .csv or > some delimited .txt file. Once that is done, all your rows/columns will > be "nice and neat" . > Once that is done, (and since your client doesn't have ACCESS, try > MYSQL or POSTGRESQL(they are open source). They can handle A LOT OF > DATA, so however big your orginal DB is, you can import it to one of > these more than capable OS freebie Databases. > > Good luck > Yeah; the only thing is that I am going to have to write a solution to give them "easy" access to their data. Sometimes, they just want to look up a row of data, but they don't want to put their data in a database server -- they want it on their machine so that it is "private" (FSVO private--it's a Windows box). -- Mike From kibleur.christophe at gmail.com Sun Nov 5 14:19:34 2006 From: kibleur.christophe at gmail.com (Tool69) Date: 5 Nov 2006 11:19:34 -0800 Subject: ANN: PyQt v4.1 Released In-Reply-To: <1162749608.733730.321970@k70g2000cwa.googlegroups.com> References: <1162749608.733730.321970@k70g2000cwa.googlegroups.com> Message-ID: <1162754374.637359.322990@m73g2000cwd.googlegroups.com> Thanks Phil, Can you put some hints about how to build QScintilla2 on Windows please ? From __peter__ at web.de Tue Nov 14 09:48:05 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Nov 2006 15:48:05 +0100 Subject: modules and generated code References: Message-ID: Nigel Rantor wrote: > So, if I have a tool that generates python code for me (in my case, > CORBA stubs/skels) in a particular package is there a way of placing my > own code under the same package hierarchy without all the code living in > the same directory structure. http://docs.python.org/lib/module-pkgutil.html Peter From grflanagan at yahoo.co.uk Sat Nov 4 02:44:20 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 3 Nov 2006 23:44:20 -0800 Subject: Programming Language that is Spreadsheet/Table Based In-Reply-To: References: <1162588208.533235.266100@k70g2000cwa.googlegroups.com> Message-ID: <1162626260.236167.157920@m73g2000cwd.googlegroups.com> James Stroud wrote: > I have spent a lot of time making a "Table" > class over about the last year and a half, but I'm not sure what might > be an intuitive interface for most people. First, I think it should work > like a "sorted" dictionary of lists, but, at the same time, a list of > sorted dictionaries. I also want *shorthand* for selection. > > For example, does the output below look like an intuitive interface? Or, > more likely, how many people get squeamish when they see this interface? > Do these squeamish people have any better ideas? This is a taste of how > my Table class currently behaves: > > py> print t # dependent on its property t.format > Last First Age > Barker Bob 204 > Burnet Carol 64 > Danson Ted 54 > Cooper Alice 78 > py> t.headings() > ("Last", "First", "Age") > py> t.get_row(1) > ['Burnet', 'Carol', 64] > py> t[1] > ['Burnet', 'Carol', 64] > py> t.get_column('Last') > ['Barker', 'Burnet', 'Danson', 'Cooper'] +1 from me up to here > py> # the following is probably the trickiest, should it return a Table > py> # should it be illegal? > py> # should t['Last'] be the way to take the "slice" and get the col? > py> t[None, 'Last'] # 1d slice returns list (2nd dim. explicit) > ['Barker', 'Burnet', 'Danson', 'Cooper'] I can imagine manipulating columns at the Table creation stage - insert, append, delete column - but after that I think you would be dealing with rows more often. Personally, if I needed columns I would be happier with a list comprehension: [ (row['Last'], row['Age']) for row in t ] etc. eg. like: http://buzhug.sourceforge.net/ > py> t2 = t[1:3, ('First', 'Age')] # 2d slice returns a new Table > py> t3 = t[1:3,'First':'Age'] # shorthand to take a swath of columns > py> t3 = t[1:3, 0:2] # if we know what column numbers we want instead t[1:3][0:2] and so on would be more intuitive to me, possibly t[1:3]['First':'Age'] > Please don't criticize unless you have a better idea > about the API of a Table. I want to hear genuine and concrete ideas and > not abstruse pontification about programming or design! Statements of "I > wouldn't do this thing here" should be immediately followed by > "--rather, I would do this other thing for which I've created a concrete > example below." chill... Gerard From bdesth.quelquechose at free.quelquepart.fr Tue Nov 7 16:22:17 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 07 Nov 2006 22:22:17 +0100 Subject: object data member dumper? In-Reply-To: <4550cddd$0$12104$88260bb3@free.teranews.com> References: <4550cddd$0$12104$88260bb3@free.teranews.com> Message-ID: <4550f442$0$20337$426a34cc@news.free.fr> tom arnall a ?crit : > does anyone know of a utility to do a recursive dump of object data members? > What are "object data members" ? (hint: in Python, everything is an object - even functions and methods). What is your real use case ? From lycka at carmen.se Thu Nov 2 06:41:58 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 02 Nov 2006 12:41:58 +0100 Subject: ANN: wxPython 2.7.1.3 In-Reply-To: References: Message-ID: robert wrote: > John Salerno wrote: >> You want Python 2.3 for Windows? > > yes. > (I know no other big libs which already stops support of py2.3-win) The general policy for Python is to support version 2.n-1 when 2.n is the current version, but not older versions than that. There was recently a 2.3.6 release with a security fix, but this is really an exception. Since Python 2.5 was released, Python 2.4 is the oldest supported Python version. I was about to give a reference to the appropriate PEP, but right now I can't for my life figure out where I read this... I'm just a bit more brain dead than usual today, due to some virus. From julvar at gmail.com Mon Nov 6 01:24:11 2006 From: julvar at gmail.com (Julian) Date: 5 Nov 2006 22:24:11 -0800 Subject: adding python scripting to my application Message-ID: <1162794251.047389.297800@e3g2000cwe.googlegroups.com> Hi, first of all, I have to say I am new to Python. I have been working with a finite element analysis program written in c++. now, I am trying to 'rebuild' this code (possibly a full re-write) with scripting capability. I did some reading on the web, and found that there are two ways to do this : extending and embedding. and I still haven't figured out what I should be using. I guess the first thing is to figure out what I am to do with the scripting capability - at the very least, I would like to run parametric analyses - run multiple analysis models by changing certain parameters using for loops. i found that the commercial fea package - abaqus uses python as well - I don't know whether they embedded or extended ? is there any way to find out? another fea application called OOF2 (http://www.ctcms.nist.gov/oof/oof2/#features) says "OOF2 is completely scriptable in Python". and I don't really understand what that means... maybe I haven't grasped the full potential of what python scripting could do for an fea program. can you tell me how to decide what path I should take - embed or extend ? or maybe some one could point me to some document/webpage that talks about this. thanks a lot, Julian. PS, my fea program uses its own script to read the analysis model information using the c++ iostream and our own parsing functions - but I don't have to stick to those function when I am writing the new code. From emin.shopper at gmail.com Thu Nov 2 17:57:29 2006 From: emin.shopper at gmail.com (emin.shopper at gmail.com) Date: 2 Nov 2006 14:57:29 -0800 Subject: emacs shell hangs on W32 with python Message-ID: <1162508249.399337.233170@m73g2000cwd.googlegroups.com> Emacs seems to freeze when doing certain shell commands on Microsoft Windows. The following is a simple example with Xemacs: ---------------------------------------------------------- [Xemacs version 21.4.19; January 2006] Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. h:\>c:\python25\python.exe -i c:\python25\python.exe -i 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 Tkinter >>> >>> >>> t = Tkinter.Tk() >>> 2 2 2 ------------------------------------------- At this point, python no longer accepts input. This example works fine when starting python through dos instead of emacs. Note, I am not using python-mode.el so that is not the problem. I also reproduced the problem with GNU Emacs (version "GNU Emacs 21.3.1 (i386-mingw-nt5.1.2600) of 2004-03-10 on NYAUMO") Is there any way to run python through emacs or xemacs without having it hang or is shell support broken? Thanks in advance, -Emin From peter.mosley at talk21.com Fri Nov 10 03:56:24 2006 From: peter.mosley at talk21.com (peter) Date: 10 Nov 2006 00:56:24 -0800 Subject: Tkinter check box behaviour - Windows / Linux discrepancy References: <1163114920.900203.306550@h48g2000cwc.googlegroups.com> Message-ID: <1163148984.394092.200530@m7g2000cwm.googlegroups.com> Thank you for those suggestions I've tried it on Windows and it seems fine (with the minor change to command=self.chkTest_click). I'm currently at work, with no access to Linux, so can't test it there until this evening. Muchas gracias! From lycka at carmen.se Mon Nov 13 11:47:30 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 13 Nov 2006 17:47:30 +0100 Subject: Python component model In-Reply-To: <1163349593.903843.167510@b28g2000cwb.googlegroups.com> References: <1163349593.903843.167510@b28g2000cwb.googlegroups.com> Message-ID: sturlamolden wrote: > There is a whole generation of computer users out there scared stiff of > using the keyboard. Soon, computers will not have a keyboard at all. > The trend is perhaps more pronounced among managers not writing code > themselves, but "taking decisions" about which tools to use. Is it just me, or does someone else feel that this is like using magnetic letters on a refrigerator door instead of a pen and paper. My two year old son thinks those magnetic letters are fun, but then he can't write at all. My seven year old has certainly switched to pen and paper (or computer) for 99% of his writing. Sure, they have their use--it might be more effective to write TENNIS with colorful letters across the fridge door in some situation, but most of the time, pen and paper is much more useful. You never run out of letters, and it's easy to draw lines or arrows, complement the text with a little picture etc. The cost for learning the skill to write readable letters is well compensated for... We recently released a toolkit for interfacing our systems with legacy systems, and very soon, people started using it in way we had never expected. I suppose that could be possible with a "visual" tool too, but it seems to me that those tools are typically fairly limited, just as computer based role-playing games are much more limited than the ones played around a table with a good flesh-and-blood game master who can respond to any idea you come up with at the spur of the moment. From vedran at v-programs.com Thu Nov 9 12:22:50 2006 From: vedran at v-programs.com (vedran at v-programs.com) Date: 9 Nov 2006 09:22:50 -0800 Subject: directpython application bug Message-ID: <1163092970.356233.184700@b28g2000cwb.googlegroups.com> Hello, I using directpython for making 3d miniature applications,but I have one problem about directpython. This is my code for example: import d3d import d3dc import d3dx device=d3d.createDevice() groundtexture=d3d.Font(u'my program',30) ...and when I run this code, directpython just open window and after few minutes close the window What to I do? Thanks!!! From theller at ctypes.org Thu Nov 9 07:27:30 2006 From: theller at ctypes.org (Thomas Heller) Date: Thu, 09 Nov 2006 13:27:30 +0100 Subject: [Ann] ctypes wiki Message-ID: <45531EB2.1000104@ctypes.org> I have installed a wiki which could / should be used to document the ctypes package and ctypes related packages (like comtypes, for example). ctypes is a foreign function library for Python: http://starship.python.net/crew/theller/ctypes/ I hope the wiki will evolve over time into a useful resource. Currently there is no actual contents - so please contribute by adding tips, tricks, and whatever you have to share about ctypes. The wiki URL is: http://starship.python.net/crew/theller/wiki Thomas From heikki at osafoundation.org Wed Nov 1 00:43:31 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Tue, 31 Oct 2006 21:43:31 -0800 Subject: Python and SSL enabled In-Reply-To: <1162328451.004606.194700@m7g2000cwm.googlegroups.com> References: <1161711493.617569.178870@h48g2000cwc.googlegroups.com> <1162328451.004606.194700@m7g2000cwm.googlegroups.com> Message-ID: matey wrote: > However, when I use the following command: python setup.py install > I get the following error: > > creating /usr/local/lib/python2.3/site-packages/M2Crypto > error: could not create > '/usr/local/lib/python2.3/site-packages/M2Crypto': Permission denied Ok, it looks like you M2Crypto built ok, but now you face this permission problem which is not specific to M2Crypto. You'd run into this with any 3rd party python module. > Since I don't have root privleges can I install the M2Crypto somewhere > else? You could manually copy the built M2Crypto directory somewhere in your home directory, for example: /home/mmedina/python2.3/site-packages/M2Crypto Then, you'd edit (or create) PYTHONPATH environment variable so that it contained /home/mmedina/python2.3/site-packages. After that you should be able to import M2Crypto in your scripts. In the future if you needed more 3rd party libs you could just place them as siblings of M2Crypto in your personal site-packages dir we created above. An alternative is to copy M2Crypto and any other 3rd party libs into the same dir where your python script is so that when you do an import, the 3rd party libs are found in the same dir. -- Heikki Toivonen From cping at dso.org.sg Fri Nov 24 02:59:12 2006 From: cping at dso.org.sg (Jeremy) Date: Fri, 24 Nov 2006 15:59:12 +0800 Subject: Newbie Developing a Python Extension Message-ID: Hi, I have been working on Linux 2.6.9 to adapt a C++ module to work as a Python extension with the following setup.py file: from distutils.core import setup, Extension sm=Extension( 'tdma', define_macros=[('__USE_POSIX199309','1')], include_dirs=['/usr/include','/usr/include/python2.3'], library_dirs=['/usr/lib'], sources=['Bitstrea.cpp','bytequeu.cpp','debug.cpp','dlist.cpp', 'GrPort.cpp','IoPort.cpp','LMEmu.cpp','LMEmuPdu.cpp', 'MacPyIf.cpp','per_os_clk.cpp','timer.cpp']) setup(name='MySm', version='0.1.0', description='TDMA MAC', ext_modules=[sm]) The extension uses the POSIX call clock_gettime() and things seem fine when generating the tdma.so file. However, when running the Python program, at a line 'from tdma import init,txdn,txup,...', I get an error message saying 'ImportError: /home/.../tdma.so: undefined symbol: clock_gettime'. What is wrong here? Is the from-import statement right? Why is it, when I use 'import sm' or 'from sm import...', I get the message 'ImportError: No module named sm'? Thanks, Jeremy From michele.simionato at gmail.com Fri Nov 10 03:12:37 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 10 Nov 2006 00:12:37 -0800 Subject: how is python not the same as java? In-Reply-To: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> Message-ID: <1163146357.902342.80730@f16g2000cwb.googlegroups.com> gavino wrote: > both are interpreted oo langauges...... Notice that gavino has a long history of asking trollish questions in Lisp and Scheme newsgroups and he displays the typical behavior of a troll. Michele Simionato From pyscripter at gmail.com Mon Nov 20 08:50:50 2006 From: pyscripter at gmail.com (PyScripter) Date: 20 Nov 2006 05:50:50 -0800 Subject: A python IDE for teaching that supports cyrillic i/o In-Reply-To: References: <20061118190104.GA29614@58sirius016.dc.ukrtel.net> <1163902308.672892.268320@k70g2000cwa.googlegroups.com> Message-ID: <1164030650.091271.160910@j44g2000cwa.googlegroups.com> Kirill Simonov wrote: > On Sat, Nov 18, 2006 at 06:11:48PM -0800, PyScripter wrote: > > Kirill Simonov wrote: > In PyScripter, > >>> print "...some cyrillic characters..." > produces output as if an UTF-8 string is displayed in latin1. > On the other hand, > >>> print u"...some cyrillic characters..." > works correctly in PyScripter. Both above examples works correctly in a > real console when sys.stdout.encoding is set to 'utf-8'. This is a problem with Python's compile function, which does not take an encoding parameter (same issue with IDLE). This issue has been discussed earlier in the Python newsgroups. However PyScripter offers an IDE option (Tools, Options, IDE options) "Use utf-8 in the interpreter". If this option is checked print u"...some cyrillic characters..." works, otherwise print "...some cyrillic characters..." works assuming you have the correct sys.getdefaultencoding(). So you have a choice! Unfortunately you cannot make both versions to work in the interactive interpreter at the same time. The "real" console takes the input from streams the encoding of which can be specified. Although this is possible in PyScripter, it is a bit of a hassle to implement, but I may do it in a future version. Please note that when you run scripts both versions will work with the right source encoding comment. > raw_input() doesn't work at all with non-ASCII characters in PyScripter. > >>> raw_input("...some cyrillic characters...") > displays the label in latin1 while > >>> raw_input(u"...some cyrillic characters...") > produces UnicodeDecodeError. > raw_input is fixed and now accepts unicode in version 1.7.2.5. Download from http://pyscripter.googlepages.com/PyScripterv1.7.2.5.zip. From gagsl-py at yahoo.com.ar Fri Nov 10 18:36:27 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 10 Nov 2006 20:36:27 -0300 Subject: handling many default values In-Reply-To: References: Message-ID: <7.0.1.0.0.20061110202730.04741d18@yahoo.com.ar> At Friday 10/11/2006 14:11, Alan G Isaac wrote: >My class MyClass reuses many default parameters >with a small number of changes in each instance. >For various reasons I decided to put all the >parameters in a separate Params class, instances >of which reset the default values based on keyword >arguments, like this: > >class Params: > def __init__(self,**kwargs): > #set lots of default values > ... > #set the deviations from defaults > self.__dict__.update(kwargs) > >Is this a reasonable approach overall? >(Including the last line.) I'm not sure what you want to do exactly, but a class attribute acts as a default instance attribute. class A(object): x = 0 y = 20 def __init__(self, x=None, y=None): if x is not None: self.x = x if y is not None: self.y = y class B(A): z = 3 def __init__(self, x=None, y=None, z=None): A.__init__(self, x, y) if z is not None: self.z = z a = A(1) print "a.x=",a.x print "a.y=",a.y b = B(z=8) print "b.x=",b.x print "b.y=",b.y print "b.z=",b.z output: a.x= 1 a.y= 20 b.x= 0 b.y= 20 b.z= 8 -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From ptmcg at austin.rr._bogus_.com Wed Nov 8 17:51:45 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 08 Nov 2006 22:51:45 GMT Subject: decorators References: <1163018240.383103.183930@b28g2000cwb.googlegroups.com> Message-ID: <5ct4h.685$mR4.482@tornado.texas.rr.com> "Carsten Haese" wrote in message news:mailman.1938.1163022175.11739.python-list at python.org... > If none of the examples make you say > "wow, I could use this" and if you don't find yourself writing > repetitive setup/teardown/housekeeping code, you can probably live quite > comfortably without using decorators. > Amen! Don't force yourself to learn decorators if you don't need them at the moment. Wait until you start repeating the same code (lock/unlock, dbready/dbcommit, logstart/logend, etc.) around multiple functions, then go back and try applying a decorator to simplify the job. Having a real use for them will make it much easier to "get". I will say, though, that I found the memoizing decorator to be especially intriguing and eye-opening, and didn't realize I needed it until I saw it laid out in front of me. -- Paul From steve at REMOVE.THIS.cybersource.com.au Wed Nov 22 06:41:25 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 22 Nov 2006 22:41:25 +1100 Subject: Is there a list comprehension for this? References: <1164143944.874745.19470@f16g2000cwb.googlegroups.com> <1164171602.525542.56750@f16g2000cwb.googlegroups.com> <1164191284.251308.316810@f16g2000cwb.googlegroups.com> Message-ID: On Wed, 22 Nov 2006 02:28:04 -0800, John Machin wrote: > > Steven D'Aprano wrote: >> On Tue, 21 Nov 2006 21:00:02 -0800, John Machin wrote: >> >> > Steven D'Aprano wrote: >> > >> > [snip] >> > >> >> def running_sum(dw): >> >> """Return a list of the running sums of sequence dw""" >> >> rs = [0]*len(dw) >> >> for i in range(len(dw)): >> >> rs[i] = dw[i] + rs[i-1] >> > >> > Please explain to the newbies why there is no exception raised when >> > rs[i-1] is executed for i == 0, and state whether you consider this is >> > a Good Idea or a Filthy Trick or a Fortunate Accident. >> >> Because rs[0-1] is just rs[-1], which fetches the LAST item of the list. I >> cunningly initialised the list to all zeroes, so adding zero to the first >> term doesn't change the result value. >> >> It is a variation of the sentinel technique, where you add an extra value >> to the beginning or end of a list so that you don't need to treat the >> first or last item differently. In this specific case, I think it is a >> combination of Good Idea and Fortunate Accident, but since the >> meaning of list[-1] is both deliberate and well-documented, it is >> certainly not a Filthy Trick. >> > > Fair enough. But it does make the concerned reader go back a couple of > lines to see why it doesn't run amok. Nobody said that every piece of code should be instantly comprehensible just at a glance. Sometimes you do actually have to think about code to understand it, even in Python :) > Here's my attempt at a > no-reader-backtracking solution: > > def running_sum_2(dw): > rs = dw[:1] > for i in xrange(1, len(dw)): > rs.append(dw[i] + rs[-1]) > return rs > > Comments invited. Even with xrange() instead of range, it is a little slower than my version for largish input lists because you are repeatedly appending to a list. >>> timeit.Timer("running_sum(L)", ... "from __main__ import running_sum; L = range(500)").timeit(1000) 0.56354999542236328 >>> timeit.Timer("running_sum_2(L)", ... "from __main__ import running_sum_2; L = range(500)").timeit(1000) 0.68534302711486816 Although the speed difference disappears (or even reverses) for small enough lists. Either way, it isn't really a major speed difference -- Python's resizing of lists is very smart. But why build a list of all the running sums when you probably only need them one at a time? Here's a generator version that can take any iterable, not just a sequence: def running_sum_3(iterable): sum_ = 0 for x in iterable: sum_ += x yield sum_ And it is considerably faster than either of the list-only versions: >>> timeit.Timer("list(running_sum_3(L))", ... "from __main__ import running_sum_3; L = range(500)").timeit(1000) 0.33915305137634277 -- Steve. From e0427417 at student.tuwien.ac.at Mon Nov 20 03:56:20 2006 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Mon, 20 Nov 2006 09:56:20 +0100 Subject: a few extensions for the itertools In-Reply-To: <1163982188.673884.255770@b28g2000cwb.googlegroups.com> References: <4560bfb0$0$10578$3b214f66@tunews.univie.ac.at> <1163982188.673884.255770@b28g2000cwb.googlegroups.com> Message-ID: <45616d56$0$10578$3b214f66@tunews.univie.ac.at> Carl Banks wrote: > Paul McGuire wrote: >> "Mathias Panzenboeck" wrote in message >> news:4560bfb0$0$10578$3b214f66 at tunews.univie.ac.at... >>> I wrote a few functions which IMHO are missing in python(s itertools). >>> >>> You can download them here: >>> http://sourceforge.net/project/showfiles.php?group_id=165721&package_id=212104 >>> >>> A short description to all the functions: >>> >> Just a couple of questions: >> >>> iproduct(iterable, start=0) -> value >>> Returns the product of the elements of a iterable >>> times the value of parameter 'start'. When the >>> iterable is empty, returns start. >>> >> Wouldn't 1 be a better default value for start? > > I concur; start should default to 1. > Bug in the documentation, not in the function. ;) From jeremy+complangpython at jeremysanders.net Thu Nov 9 12:34:10 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Thu, 09 Nov 2006 17:34:10 +0000 Subject: How to choose the right GUI toolkit ? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163092380.301382.113470@m7g2000cwm.googlegroups.com> Message-ID: Dan Lenski wrote: > Nick and John S., thank you for the tip on wxPython! I'll look into it > for my next project. I too would avoid Qt, not because of the GPL but > simply because I don't use KDE under Linux and because Qt is not well > supported under Cygwin or on native Windows. I too like to learn from > actual printed books, so I'll check this one out. O'Reilly should do a > book on Python GUI stuff! PyQt is well supported under native Windows. Qt-4 is now GPLd for Windows too. I'd highly recommend it. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From mfein2 at earthlink.net Thu Nov 2 09:54:04 2006 From: mfein2 at earthlink.net (mattf) Date: 2 Nov 2006 06:54:04 -0800 Subject: Python in sci/tech applications Message-ID: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> I've discovered Python and have been trying it out lately as a possible replacement for computations that would ordinarily be done with a commercial package like Matlab or IDL. I'd like to mention a few things I've run across that have either surprised me or kept me from doing things the way I'd like to. 1) -There's a large and active sci/tech Python community out there.- This was something of a surprise. If you look at the python.org site and click down a couple of levels past the front page, there's a rather brief mention of scientific and numeric applications-- but I don't think this does justice to the current levels of activity and accomplishment. 2) -There's a very impressive set of libraries out there- NumPy, SciPy, Enthought. It's really kind of stunning how mature these libraries are and how much I had to poke around to figure that out. 3) -There's a problem with development under Windows. A typical task will entail writing a 'pure python' prototype to get the 'data in, data out' part of a problem straightened out, then writing a module in C to get adequate performance in production runs. But the C compiler that my employer provides (the current version of MSVS) doesn't produce libraries that work with the current version of Python. Ooops. This, in the real world, is a big problem. I -love- Python. And I think I could convince other people to use it. But I've got to have a way to produce compiled modules painlessly, i.e., without installing a new operating system. From spe.stani.be at gmail.com Mon Nov 6 18:45:22 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 6 Nov 2006 15:45:22 -0800 Subject: wing ide vs. komodo? In-Reply-To: References: <2nRXg.108$1n3.2866@news.tufts.edu> <18SXg.27347$Go3.9933@dukeread05> Message-ID: <1162856722.569478.68120@f16g2000cwb.googlegroups.com> gblais at cox.net schreef: > I have both, but the IDE I use every day is SPE, which is shareware. I'm > not savvy enough to enumerate a feature comparison, but I do find SPE > extremely friendly and intuitive. > > Gerry SPE is not shareware. It is open-source, gpl-licensed freeware. Donations however never hurt. Stani -- http://pythonide.stani.be From fredrik at pythonware.com Wed Nov 22 13:51:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Nov 2006 19:51:39 +0100 Subject: utf - string translation In-Reply-To: References: Message-ID: hg wrote: > We noticed that len('?') != len('a') sounds odd. >>> len('?') == len('a') True are you perhaps using an UTF-8 editor? to keep your sanity, no matter what editor you're using, I recommend adding a coding directive to the source file, and using *only* Unicode string literals for non-ASCII text. or in other words, put this at the top of your file (where "utf-8" is whatever your editor/system is using): # -*- coding: utf-8 -*- and use u'' for all non-ASCII literals. From dhwild at talktalk.net Wed Nov 22 17:16:41 2006 From: dhwild at talktalk.net (David H Wild) Date: Wed, 22 Nov 2006 22:16:41 +0000 (GMT) Subject: utf - string translation References: <1164224962.711265.198090@h48g2000cwc.googlegroups.com> <1164226304.119425.206380@h54g2000cwb.googlegroups.com> <1164232741.215312.322990@k70g2000cwa.googlegroups.com> Message-ID: <4564dd7b$0$1349$834e42db@reader.greatnowhere.com> In article <1164232741.215312.322990 at k70g2000cwa.googlegroups.com>, John Machin wrote: > So why do you want to strip off accents? The history of communication > has several examples of significant difference in meaning caused by > minute differences in punctuation or accents including one of which you > may have heard: a will that could be read (in part) as either "a chacun > d'eux million francs" or "a chacun deux million francs" with the > remainder to a 3rd party. The difference there, though, is a punctuation character, not an accent. -- David Wild using RISC OS on broadband From breakfastea at gmail.com Sat Nov 11 04:57:14 2006 From: breakfastea at gmail.com (Camellia) Date: 11 Nov 2006 01:57:14 -0800 Subject: UnboundLocalError In-Reply-To: References: <1163083074.786927.184170@i42g2000cwa.googlegroups.com> <1163223355.190176.127030@h48g2000cwc.googlegroups.com> <1163232187.747318.132260@m73g2000cwd.googlegroups.com> Message-ID: <1163239034.138715.189970@b28g2000cwb.googlegroups.com> Oh thank you for pointing that out Fredrik, you made the case more clear:) On Nov 11, 7:19 pm, Fredrik Lundh wrote: > Camellia wrote: > > Oh how can I thank you enough, you make my day:) > > According to what you said I finally figure it out, it is the same as: > > > > > b = 1 > > def a(): > > b = b #no good:) > > if you really want to modify a variable that lives outside the function, > you can use the "global" directive: > > http://effbot.org/pyfaq/how-do-you-set-a-global-variable-in-a-functio... > > > So in every day programming I should avoid using the same name for > > different types of objects because they will step on each other, > > right? > > if you want to distinguish between things, giving them distinct names is > always a good idea. > > From rrs at researchut.com Sat Nov 25 18:27:26 2006 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: 25 Nov 2006 15:27:26 -0800 Subject: screen output problem Message-ID: <1164497246.626735.254050@h54g2000cwb.googlegroups.com> Hi, I have, for very long, been trying to find a consistent solution (which could work across major python platforms - Linux, Windows, Mac OS X) for the following problem. I have a function which downloads files from the web. I've made the function threaded. I'm trying to implement a progress bar for it which could work across all the platforms. The problem is that when the progress bar is displayed, all the threads overwrite the progress bar. I've thought of using curses but AFAIK curses is not available for Windows. Is there a generic way to accomplish the following: progress = "[===================]\n[=======================]" for x in range(5): sys.stdout.write(progress + "\r") Basically, I want a way through which I want to display data on two lines and make sure that "\r" overwrites the two lines without putting a newline making sure that whatever library it uses is available across all major Python platforms. Thanks, Ritesh From jseigh_01 at xemaps.com Tue Nov 7 16:13:33 2006 From: jseigh_01 at xemaps.com (Joe Seigh) Date: Tue, 07 Nov 2006 16:13:33 -0500 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <4550F2AE.1010205@v.loewis.de> References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <7xk62ct5pf.fsf@ruckus.brouhaha.com> <1162913881.953664.254960@m73g2000cwd.googlegroups.com> <1162922230.992249.52430@f16g2000cwb.googlegroups.com> <4550cc64$0$3462$9b622d9e@news.freenet.de> <1162928970.223276.72600@h48g2000cwc.googlegroups.com> <4550F2AE.1010205@v.loewis.de> Message-ID: Martin v. L?wis wrote: > You still didn't say what you would suggest to make it thread-safe > again; most likely, you proposal would be to add locking. If I > understand Joe's approach correctly, he has a solution that does > not involve locking (although I don't understand how it works). > Sun had applied for a patent on it. You can go to the uspto search page here http://www.uspto.gov/patft/index.html and look for 20060218561 Code preparation technique employing lock-free pointer operations 20060037026 Lightweight reference counting using single-target synchronization Click on the images link on the patent application where the illustrations are which show the concepts probably better than the text. The first one above is actually a continuation patent on three different techniques. One using double wide compare and swap, one using ROP (Repeat Offender Problem), a form of PDR, and one using DCAS (compare and swap of two separate locations) which only exists on MC68020 and MC68030 processors. -- Joe Seigh When you get lemons, you make lemonade. When you get hardware, you make software. From __peter__ at web.de Tue Nov 28 07:46:50 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Nov 2006 13:46:50 +0100 Subject: How to increase the speed of this program? References: <1164699156.682944.97410@j44g2000cwa.googlegroups.com> <1164706548.778583.267730@n67g2000cwd.googlegroups.com> <1164714786.086910.288450@45g2000cws.googlegroups.com> Message-ID: Fredrik Lundh wrote: > John Machin wrote: > >> I'm extremely agnostic about the spelling :-) IOW I'd be very glad of >> any way [pure Python; e.g. maintaining my own version of the array >> module doesn't qualify] to simply and rapidly create an array.array >> instance with typecode t and number of elements n with each element >> initialised to value v (default to be the zero appropriate to the >> typecode). > > array(t, [v])*n Of course Leo was already there before I messed it up again. $ python2.5 -m timeit -s'from array import array; s = "abc"' 'a = array("c", s); a*1000000' 10 loops, best of 3: 53.5 msec per loop $ python2.5 -m timeit -s'from array import array; s = "abc"' 'a = array("c", s); s*1000000' 100 loops, best of 3: 7.63 msec per loop So str * N is significantly faster than array * N even if the same amount of data is copied. Peter From cameron.walsh at gmail.com Tue Nov 28 02:53:11 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Tue, 28 Nov 2006 15:53:11 +0800 Subject: splitting a long string into a list In-Reply-To: <1164698637.721659.169240@n67g2000cwd.googlegroups.com> References: <1164692082.272978.66720@14g2000cws.googlegroups.com> <1164698637.721659.169240@n67g2000cwd.googlegroups.com> Message-ID: ronrsr wrote: > still having a heckuva time with this. > > here's where it stand - the split function doesn't seem to work the way > i expect it to. > > > longkw1,type(longkw): Agricultural subsidies; Foreign > aid;Agriculture; Sustainable Agriculture - Support; Organic > Agriculture; Pesticides, US, Childhood Development, Birth Defects; > 1 > > longkw.replace(',',';') > > Agricultural subsidies; Foreign aid;Agriculture; Sustainable > Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood > Development Here you have discovered that string.replace() returns a string and does NOT modify the original string. Try this for clarification: >>> a="DAWWIJFWA,dwadw;djwkajdw" >>> a 'DAWWIJFWA,,,,,,dwadw;djwkajdw' >>> a.replace(",",";") 'DAWWIJFWA;;;;;;dwadw;djwkajdw' >>> a 'DAWWIJFWA,,,,,,dwadw;djwkajdw' >>> b = a.replace(',',';') >>> b 'DAWWIJFWA;;;;;;dwadw;djwkajdw' > > > kw = longkw.split("; ,") #kw is now a list of len 1 Yes, because it is trying to split longkw wherever it finds the whole string "; '" and NOT wherever it finds ";" or " " or ",". This has been stated before by NickV, Duncan Booth, Fredrik Lundh and Paul McGuire amongst others. You will need to do either: a.) # First split on every semicolon a = longkw.split(";") b = [] # Then split those results on whitespace #(the default action for string.split()) for item in a: b.append(item.split()) # Then split on commas kw = [] for item in b: kw.append(item.split(",")) or b.) # First replace commas with spaces longkw = longkw.replace(",", " ") # Then replace semicolons with spaces longkw = longkw.replace(";", " ") # Then split on white space, (default args) kw = longkw.split() Note that we did: longkw = longkw.replace(",", " ") and not just: longkw.replace(",", " ") You will find that method A may give empty strings as some elements of kw. If so, use method b. Finally, if you have further problems, please please do the following: 1.) Provide your input data clearly, exactly as you have it. 2.) Show exactly what you want the output to be, including any special cases. 3.) If something doesn't work the way you expect it to, tell us how you expect it to work so we know what you mean by "doesn't work how I expect it to" 4.) Read all the replies carefully and if you don't understand the reply, ask for clarification. 5.) Read the help functions carefully - what the input parameters have to be and what the return value will be, and whether or not it changes the parameters or original object. Strings are usually NOT mutable so any functions that operate on strings tend to return the result as a new string and leave the original string intact. I really hope this helps, Cameron. From fredrik at pythonware.com Sat Nov 11 21:08:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Nov 2006 03:08:02 +0100 Subject: reduce to be removed? In-Reply-To: <1163295752.701124.322620@h54g2000cwb.googlegroups.com> References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163288885.884417.218270@f16g2000cwb.googlegroups.com> <1163290526.013063.245130@m7g2000cwm.googlegroups.com> <1163295752.701124.322620@h54g2000cwb.googlegroups.com> Message-ID: Dustan wrote: >>>> foo =\ > [[[1,2,3],[4,5,6],[7,8,9]], > [[3,2,1],[6,5,4],[9,8,7]]] > > Here, foo appears to be a 3-dimensional list - except it's supposed to > be 2-dimensional. The inner-list-of-lists is a result of how I'm > producing the data, and now I want to do a mass-concatenation (or > extending) of the inner-list-of-lists, and come up with this result: > >>>> foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]] > True that still doesn't explain your "the expression must be used in a list comprehension" requirement, though. assuming that the sizes are varying, and at least sometimes a lot larger than 3x3, I'd probably write the above as for index, item in enumerate(foo): this = [] for i in item: this.extend(i) foo[index] = this which should be pretty efficient, since it avoids unnecessary function calls, and is amortized linear time instead of O(N**2). or, if I was in a hurry, and didn't really care if the inner sequences were lists or tuples: foo = map(Tkinter._flatten, foo) From __peter__ at web.de Thu Nov 2 15:44:06 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Nov 2006 21:44:06 +0100 Subject: what's the difference between these two methods? (aka, why doesn't one of them work?) References: <1162499293.080529.5480@m73g2000cwd.googlegroups.com> Message-ID: JohnJSal wrote: > Can someone explain to me why the first version of this method works, > but the second one doesn't? All I've changed (I think) is how the > information is nested. The error I'm getting is that the call to > xrc.XRCCTRL is not working in the second example. Instead of getting > the appropriate widget, it's returning None. Is this a result of the > nesting, or the for loops perhaps? > > Thanks. > > > def OnSaveRecord(self, event): > textfield_values = [] > for tab in self.notebook.GetCurrentPage().GetChildren(): > for table in self.get_textfield_ids(): > table_values = [] > for textfield_id in table: Put in a print textfield_id here. You'll see an 'n' before the exception occurs, because... > table_values.append(xrc.XRCCTRL(tab, > textfield_id).GetValue()) > textfield_values.append(table_values) > self.save_to_database(textfield_values) > > def get_textfield_ids(self): > return (('firstName', 'middleName', 'lastName', 'birthMonth', > 'birthDay', 'birthYear', 'country', 'state', 'city'), > ('jobTitle', 'salary', 'labBuilding', 'labRoom', > 'labPhone'), > ('localAddress', 'foreignAddress', 'emailAddress', > 'homePhone', > 'foreignPhone', 'cellPhone'), ('university1', > 'yearStart1', > 'yearEnd1', 'degree1', 'university2', 'yearStart2', > 'yearEnd2', > 'degree2', 'university3', 'yearStart3', 'yearEnd3', > 'degree3', > 'university4', 'yearStart4', 'yearEnd4', 'degree4'), > ('notes')) ...the above is not a 1-tuple, but an ordinary string. You forgot the trailing comma: ('notes',) Peter From horpner at yahoo.com Wed Nov 1 11:46:17 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 1 Nov 2006 17:46:17 +0100 Subject: Style for modules with lots of constants References: <1162398506.919161.145290@m7g2000cwm.googlegroups.com> Message-ID: On 2006-11-01, bearophileHUGS at lycos.com wrote: > Neil Cerutti: >> scriptref = glk.fileref_create_by_prompt('Transcript+TextMode', >> 'WriteAppend', 0) > > That "+" sign seems useless. A space looks enough to me. The > functions can accept case-agnostic strings and ignore spaces > inside them. Example: > ('transcript textmode ', 'writeappend', 0) That's pretty cool. Not as pretty, but easier for users, possibly. >> Parsing the combinable bitfield contants might be slowish, >> though. > > I think you have to test if this is true for your situation. > Management of interned strings is probably fast enough > (compared to the rest of things done by the Python interpreter) > for many purposes. Agreed. I meant I'd have to later test if it's were fast enough. -- Neil Cerutti From johnjsal at NOSPAMgmail.com Mon Nov 6 16:57:58 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 06 Nov 2006 16:57:58 -0500 Subject: assigning values in __init__ Message-ID: <454faf57$0$12993$c3e8da3@news.astraweb.com> Let's say I'm making a game and I have this base class: class Character(object): def __init__(self, name, stats): self.name = name self.strength = stats[0] self.dexterity = stats[1] self.intelligence = stats[2] self.luck = stats[3] Is this a good way to assign the values to the different attributes? Should 'stats' be a list/tuple (like this), or should I do *stats instead? I'm trying to think ahead to when I might want to add new attributes, and I want to make sure this doesn't get crazy with individual parameters instead of just the one list. Or maybe there's some way to loop through two lists (the stats and the attributes) and assign them that way? I was thinking of a nested for statement but that didn't seem to work. From python.list at tim.thechases.com Wed Nov 1 15:28:01 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 01 Nov 2006 14:28:01 -0600 Subject: Style for modules with lots of constants In-Reply-To: References: Message-ID: <45490351.7090508@tim.thechases.com> >> The reason I used instances instead of just the Constants >> class was so that I could define a little more descriptive >> context for the constants, > > Sorry I don't know what you mean here, could I have an example It helps in the recognition if you have separation between something like turnDirection.LEFT and alignment.LEFT They may be the same or different value for LEFT, but by grouping them in a "descriptive context", it's easy to catch mistakes such as paragraph.align(turnDirection.LEFT) when what you want is paragraph.align(alignment.LEFT) and, as an added bonus, prevents name clashes such as turnDirection.LEFT = 2 alignment.LEFT = 0 With the grab-bag o' constants, you have to use old-school C-style in your modern name-space'd Python: gboc.TURN_LEFT = 2 gboc.ALIGN_LEFT = 0 or even worse, you'd end up with cruftage where you have gboc.LEFT = 2 gboc.ALIGN_LEFT = 0 #created a month later as needed and then accidentally call paragraph.align(gboc.LEFT) when you mean paragraph.align(gboc.ALIGN_LEFT) This is what I understand the grandparent's post to be referring to by "descriptive context". -tkc From ginstrom at tree.odn.ne.jp Mon Nov 6 04:39:37 2006 From: ginstrom at tree.odn.ne.jp (Ryan Ginstrom) Date: Mon, 6 Nov 2006 18:39:37 +0900 Subject: Classes referencing each other In-Reply-To: Message-ID: <20061106094002729.HSQQ.203523.t-mta2.odn.ne.jp@mta2.odn.ne.jp> > Behalf Of Manuel Bleichner > In a module I have a huge number of classes of the form: > > class A(object): > connected_to = [B, C] > > > class B(object) > connected_to = [C] > > > class C(object) > connected_to = [A] > > > As you see, classes A and B reference classes that are not > yet defined when the class is being defined. > It will raise a NameError: 'B'. How about a connection broker? Simple example: ############################# connections = {} def Register( obj ): try: connections[obj.name]['obj'] = obj except KeyError: connections[obj.name] = { 'obj' : obj, 'connected_to' : [] } def ConnectTo( objname, obj ): try: connections[objname]['connected_to'].append( obj ) except KeyError: connections[objname] = { 'obj' : None, 'connected_to' : [obj] } class ConnectionObject: def __str__(self): return self.name class A(ConnectionObject): def __init__(self): self.name = 'A' Register( self ) ConnectTo( 'B', self ) class B(ConnectionObject): def __init__(self): self.name = 'B' Register( self ) ConnectTo( 'A', self ) ConnectTo( 'C', self ) class C(ConnectionObject): def __init__(self): self.name = 'C' Register( self ) ConnectTo( 'A', self ) a = A() b = B() c = C() for (key, val) in connections.iteritems(): print 'object: %s (%s)' % ( key, val['obj'] ) str_vals = [] for obj in val['connected_to']: str_vals.append( str( obj ) ) print '\tconnections from:', str_vals ############################# Output: object: A (A) connections from: ['B', 'C'] object: C (C) connections from: ['B'] object: B (B) connections from: ['A'] object: D (None) connections from: ['C'] Regards, Ryan Ginstrom From walterbyrd at iname.com Fri Nov 17 20:56:43 2006 From: walterbyrd at iname.com (walterbyrd) Date: 17 Nov 2006 17:56:43 -0800 Subject: What do I look for in a shared Python host? Message-ID: <1163815003.733525.6380@b28g2000cwb.googlegroups.com> For example: - If I want to use Django, I need either FastCGI or Apache 2.X/mod_python 3.x - if I want to use TurboGears, I need Python 2.4: not 2.3 and not 2.5 - I have just learned that some hosters have T&Cs that forbid long running processes. I am not sure exactly what that means. Except I understand it can be a problem if using Cherrypy/TurboGears - I have read that mod_python before 3.x can be difficult What other "gotchas" would I look for? From horpner at yahoo.com Tue Nov 21 10:35:12 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 21 Nov 2006 16:35:12 +0100 Subject: interleaving dictionary values References: <1164119672.455899.292380@e3g2000cwe.googlegroups.com> Message-ID: On 2006-11-21, j1o1h1n at gmail.com wrote: > I had in mind something like this: > >>>> interleave([1, 2, 3], [4,5], [7, 8, 9]) > [1, 4, 7, 2, 5, 8, 3, 9] > > [...] before giving up and going back to trusty old map(), long > celebrated for making code hard to read: > >>>> map(None, [1, 2, 3], [4,5], [7, 8, 9]) > [(1, 4, 7), (2, 5, 8), (3, None, 9)] > > This is basically it. It then becomes: > >>>> filter(None, flatten(map(None, [1, 2, 3], [4,5], [7, 8, 9]))) > [1, 4, 7, 2, 5, 8, 3, 9] You can use itertools.chain instead of flatten: >>> from itertools import chain >>> filter(None, chain(*map(None, [1, 2, 3], [4, 5], [7, 8, 9]))) [1, 4, 7, 2, 5, 8, 3, 9] > Trouble is then getting map() to play with the result of dict.values(). > I only worked this out while writing this post, of course. > > Given a dictionary like d = { "a" : [1, 2, 3], "b" : [4, 5], "c" : [7, > 8, 9]} - I was hoping to do this: > > map(None, d.values()) You need the * to "unpack" the list. It has generally taken the place of apply. >>> map(None, *d.values()) [(1, 7, 4), (2, 8, 5), (3, 9, None)] > So... my bit of code becomes: >>> filter(None, chain(*map(None, *d.values()))) [1, 7, 4, 2, 8, 5, 3, 9] I don't think that the specific ordering that's achieved has any valuable significance. You might be just as happy with the simpler: >>> list(chain(*d.values())) [1, 2, 3, 7, 8, 9, 4, 5] -- Neil Cerutti Weight Watchers will meet at 7 p.m. Please use large double door at the side entrance. --Church Bulletin Blooper From vania.cIlli at gmail.com Thu Nov 23 07:32:45 2006 From: vania.cIlli at gmail.com (Vania) Date: 23 Nov 2006 04:32:45 -0800 Subject: socket.error connection refused In-Reply-To: References: Message-ID: <1164285165.811809.175040@j72g2000cwa.googlegroups.com> Hi, the reason I mentioned the socket is because that is where the error eventually occurs. the code I tried manually (with different urls including a local one) is the following: import urllib fo=urllib.urlopen("http://www.google.com") the error I get is: File "", line 1, in ? File "C:\Python24\lib\urllib.py", line 82, in urlopen return opener.open(url) File "C:\Python24\lib\urllib.py", line 190, in open return getattr(self, name)(url) File "C:\Python24\lib\urllib.py", line 313, in open_http h.endheaders() File "C:\Python24\lib\httplib.py", line 798, in endheaders self._send_output() File "C:\Python24\lib\httplib.py", line 679, in _send_outp self.send(msg) File "C:\Python24\lib\httplib.py", line 646, in send self.connect() File "C:\Python24\lib\httplib.py", line 630, in connect raise socket.error, msg IOError: [Errno socket error] (10061, 'Connection refused') Tim Williams ha scritto: > On 23 Nov 2006 04:09:18 -0800, Vania wrote: > > Hi, I'm not sure this is the proper forum but I try nevertheless. > > The problem I'am facing is that the socket library always fail to > > connect to an URL. The net effect is that I can not use setuptools. > > I'm using Python2.4 on a windows XPPRO Sp2 machine. > > The firewall is disabled. > > There is no NLTM proxy. > > I connect to the internet through a NAT server (and it works). > > Other than with easy_install I tried to connect to a number of external > > urls > > (all of them running) and even to localhost, > > directly in script using urllib > > and the error is always the same errno: 10061 connection refused. > > Any ideas? > > A socket can't connect to a URL, a URL is an absolute location of an > internet resource, eg hostname + (virtual) location on a server + page > name. A socket can connect to an IP address or hostname - which is > the first part of the URL after the "http://" (or ftp:// etc) > > You need to post a code snippet and the errors you are getting. From martin at v.loewis.de Tue Nov 7 13:11:47 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 07 Nov 2006 19:11:47 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <1162922230.992249.52430@f16g2000cwb.googlegroups.com> References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <7xk62ct5pf.fsf@ruckus.brouhaha.com> <1162913881.953664.254960@m73g2000cwd.googlegroups.com> <1162922230.992249.52430@f16g2000cwb.googlegroups.com> Message-ID: <4550cc64$0$3462$9b622d9e@news.freenet.de> Ross Ridge schrieb: > The thread that shares it increments the reference count before passing > its address to directly another thread or indirectly through a shared > container. To make a specific example, consider this fragment from Objects/fileobject.c: static PyObject * file_repr(PyFileObject *f) { if (PyUnicode_Check(f->f_name)) { ... Now, assume there wasn't a GIL protecting this all, and also assume f_name was a mutable member (which it currently isn't). Then, this access wouldn't be thread-safe: This code roughly translates to reg_x = f->f_name push reg_x call PyUnicode_Check (assuming this was a function and not a macro) Meanwhile, another process might perform old = f->f_name; f->f_name = new; Py_DECREF(old); i.e. change the file name. Now, it might be that they interleave this way: reg_x = f->f_name old = f->f_name f->f_name = new Py_DECREF_old push reg_x call PyUnicode_Check which would now operate on a deallocated object. To fix this, one might think that we need Py_INCREF(f->f_name) if(Py_UnicodeCheck(f->f_name)) ... Py_DECREF(f->f_name) However, this would not help, because the first incref translates to reg_x = f->f_name LOCK INC f->ob_refcnt which again leaves a race condition where the INCREF operation comes "too late". How would you propose to fix file_repr to prevent such a race condition? Regards, Martin From fredrik at pythonware.com Thu Nov 2 11:49:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 02 Nov 2006 17:49:19 +0100 Subject: other ways to check for ? In-Reply-To: <1162484302.234145.245320@e3g2000cwe.googlegroups.com> References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> <1162477269.980535.202320@h48g2000cwc.googlegroups.com> <1162478431.624590.29290@m7g2000cwm.googlegroups.com> <1162484302.234145.245320@e3g2000cwe.googlegroups.com> Message-ID: elderic wrote: > I never said that I need anything - I merely asked for alternatives. =) > I'm pretty happy with the types-module or the callable() test. > > Basically it's just for wrapping the creation of Tk-Buttons, etc. > They need a callback and in my process to learn I wanted to know about > the possible options to test for that. the more reason not to even think about using anything but "callable". many things in Python are callable; an explicit function test would disallow several interesting alternatives: >>> def foo(): ... pass ... >>> class fum: ... def bar(self): ... pass ... def __call__(self): ... pass ... >>> type(foo) is type(fum) False >>> f = fum() >>> type(foo) is type(f) False >>> type(foo) is type(f.bar) False etc. (and I really shouldn't ask why you cannot just use Tkinter, and spend your time and energy on something more worthwhile ? if not else, there are plenty of Tk extensions that could need nice wrappers...) From steve at holdenweb.com Thu Nov 16 05:40:48 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Nov 2006 10:40:48 +0000 Subject: Python v PHP: fair comparison? In-Reply-To: <1a2e01c7090d$f074cdc0$0301a8c0@tmesa.com> References: <455ba1a9$0$4218$426a74cc@news.free.fr> <1a2e01c7090d$f074cdc0$0301a8c0@tmesa.com> Message-ID: bruce wrote: > ummm bruno... > > you don't 'need' apache to run php. > > in fact, although i'm from the old hard c/c++ world.... way before web apps, > i haven't really found much for most general apps (not ui/not threaded > stuff) that php can't do.. You simply haven't been looking hard enough. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From johnjsal at NOSPAMgmail.com Thu Nov 9 15:10:07 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 09 Nov 2006 15:10:07 -0500 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> Message-ID: <45538b0d$0$26485$c3e8da3@news.astraweb.com> Michael Hobbs wrote: > Anyway, the FAQ answer seems to be a > weak argument to me. I agree. I was expecting something more technical to justify the colon, not just that it looks better. From sjmachin at lexicon.net Wed Nov 1 16:07:12 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Nov 2006 13:07:12 -0800 Subject: CSV module, DictReader problem (bug?) References: Message-ID: <1162415232.190913.163240@m73g2000cwd.googlegroups.com> Jeff Blaine wrote: > It's been a year or so since I written Python code, so maybe > I am just doing something really dumb, but... > > Documentation > ============= > > class DictReader(csvfile[,fieldnames=None, > [,restkey=None[, restval=None[, dialect='excel' > [, *args, **kwds]]]]]) > > > Create an object which operates like a regular reader > but maps the information read into a dict whose keys > are given by the optional fieldnames parameter. If the > fieldnames parameter is omitted, the values in the > first row of the csvfile will be used as the fieldnames. > > Code > ==== > > import csv > > r = csv.DictReader('C:\Temp\Book1.csv') Problem 1: """csvfile can be any object which supports the iterator protocol and returns a string each time its next method is called -- file objects and list objects are both suitable. If csvfile is a file object, it must be opened with the 'b' flag on platforms where that makes a difference.""" So, open the file, so that the next() method returns the next chunk of content, not the next byte in the name of the file. Note that the arg is called "csvfile", not "csvfilename". Problem 2: [OK in this instance, but that's like saying you have taken one step in a minefield and are still alive] backslashes and Windows file names: If you were to write 'c:\temp\book1.csv', it would blow up ... because \t -> tab and \b -> backspace. Get into the habit of *always* using raw strings r'C:\Temp\Book1.csv' for Windows file names (and re patterns). You could use double backslashing 'C:\\Temp\\Book1.csv' but it's uglier. > print r.next() > # EOF > > Output > ====== > > {'C': ':'} HTH, John From egbert.bouwman at hccnet.nl Wed Nov 29 17:21:21 2006 From: egbert.bouwman at hccnet.nl (egbert) Date: Wed, 29 Nov 2006 23:21:21 +0100 Subject: SPE refuses. In-Reply-To: <1164828687.755193.4900@l39g2000cwd.googlegroups.com> References: <1164828687.755193.4900@l39g2000cwd.googlegroups.com> Message-ID: <20061129222121.GA24634@hccnet.nl> On Wed, Nov 29, 2006 at 11:31:27AM -0800, SPE - Stani's Python Editor wrote: > If wxPython is rightly installed, which means that "import wx" works > fine and "wx.VERSION" gives the right version, you can ignore the > wxPython warning. > In a Python shell the commands 'import wx' and 'wx.VERSION' give: (2,6,3,2,'') > Please cd do your site-packages directory and do "python SPE.py > --debug" and see the error message. In gnome-terminal /usr/lib/python2.4/site-packages/_spe the command: 'python SPE.py --debug' produces the same error: You need to install at least wxPython v2.5.4.1 to run SPE. Get it from http://www.python.org Well, I got it from the debian repositories. e. -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From clodoaldo.pinto at gmail.com Wed Nov 15 07:17:01 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto Neto) Date: 15 Nov 2006 04:17:01 -0800 Subject: Problem reading with bz2.BZ2File(). Bug? In-Reply-To: References: <1163591526.029090.321390@i42g2000cwa.googlegroups.com> Message-ID: <1163593020.979114.73260@i42g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Clodoaldo Pinto Neto wrote: > > > The offending file is 5.5 MB. Sorry, i could not reproduce this problem > > with a smaller file. > > but surely you can post the repr() of the last two lines? This is the output: $ python bzp.py line number: 588317 '\x07' '' Clodoaldo From spe.stani.be at gmail.com Wed Nov 1 10:31:26 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 1 Nov 2006 07:31:26 -0800 Subject: ANN: SPE 0.8.3.c Python IDE editor In-Reply-To: <1162234468.199971.134690@m7g2000cwm.googlegroups.com> References: <1162206008.469787.270830@m73g2000cwd.googlegroups.com> <1162213852.270705.275740@b28g2000cwb.googlegroups.com> <1162234468.199971.134690@m7g2000cwm.googlegroups.com> Message-ID: <1162395086.009206.45020@f16g2000cwb.googlegroups.com> I checked the berlios site and it seems to be working. Or do you have another problem? Stani Chris Seymour schreef: > Hi Stani, > Not able to reach Berlios. The SourceForge page does not have the > Windows installer. Any ideas when it will be available? > > Thanks. > > Chris > Bernard wrote: > > thanks Stani! > > > > SPE - Stani's Python Editor wrote: > > > This is a maintenance release (mostly bug fixing) to prove that SPE is > > > alive and well! In case you are using wxPython2.7 you'll need to > > > upgrade to this release. Submitted patches will be reviewed and > > > included if approved for next release. Thanks for all your patient > > > support and continuing donations. > > > > > > The SPE 0.8.2.a release got downloaded 110550 times on berlios and > > > sourceforge together. Not bad. This means SPE has not seen an update > > > for a while or is getting very popular. Maybe both ;-) > > > > > > Installers are available for python 2.3, 2.4 and 2.5 for Windows and as > > > a rpm including wxPython. Other operating systems can choose the > > > no-setup.zip or targ.gz archives. A .deb archive is being prepared for > > > Debian Linux systems such as Ubuntu. > > > > > > wxGlade is unfortunately not compatible with wxPython2.7. So if you > > > want to use, you'll need wxPython2.6. > > > > > > :**Fixes**: > > > > > > - output is now done with a fixed font > > > - uml.py is now again a stand alone demo > > > - upgraded and fixed wxGlade > > > - fixed for wxPython2.7 (and still backwards compatible with > > > wxPython2.6) > > > - updated NotebookCtrl > > > > > > :**Contributors**: > > > > > > - Andrea Gavana (NoteBookCtrl) > > > - Alberto Griggio (wxGlade) > > > - Michael Foord (python 2.3 + 2.5 releases for windows) > > > > > > :**Donations**: > > > > > > The development of SPE is driven by donations. Each of these donors > > > receives the pdf manual in thanks for their support of SPE. > > > > > > - James Carroll (60 euro) > > > - John DeRosa (50 euro) > > > - Fumph LLC (50 euro) > > > - Ronald Britton (40 euro) > > > - David Downes (40 euro) > > > - Jorge Carrillo (40 euro) > > > - Nicolas Berney (40 euro) > > > - Francois Schnell (30 euro) > > > - Olivier Cortes (30 euro) > > > - Ayrshire Business Consulting Limited (30 euro) > > > - Chris White (25 euro) > > > - Thomas Wengerek (20 euro) > > > - John Rudolph (20 euro) > > > - Michael O'Keefe (20 euro) > > > - Michael Brickenstein (20 euro) > > > - Richard Walkington (20 euro) > > > - Oliver Tomic (20 euro) > > > - Jose Maria Cortes Arnal (20 euro) > > > - Jeffrey Emminger (20 euro) > > > - Eric Pederson (20 $) > > > - Charles Bosson (15 euro) > > > - Angelo Caruso (15 euro) > > > - Chris Hengge (15 $) > > > - Loïc Allys (15 euro) > > > - Marcin Chojnowski (15 euro) > > > - Boris Krasnoiarov (15 euro) > > > - Paul Furber (15 euro) > > > - Gary Robson (15 euro) > > > - Ralf Wieseler (15 euro) > > > - Samuel Schulenburg (10 euro) > > > - Leland Hulbert II (10 euro) > > > - Javier De La Mata Viader (10 euro) > > > - Dorman Musical Instruments (10 euro) > > > - Jaroslaw Sliwinski (10 euro) > > > - Alessandro Patelli (10 euro) > > > - James Pretorius (10 euro) > > > - Richard Wayne Garganta (10 euro) > > > - Maurizio Bracchitta (10 euro) > > > - Larry Lynch (10 euro) > > > - Kay Fricke (10 euro) > > > - Henrik Binggl (10 euro) > > > - Jerol Harrington (10 euro) > > > - Victor Adan (10 euro) > > > - James Fuqua (10 euro) > > > - Christian Seberino (5 euro) > > > - Serge Smeesters (5 euro) > > > - Jarek Libert (5 euro) > > > - Robin Friedrich (5 euro) > > > - Udo Rabe (5 euro) > > > - Roch Leduc (4 euro) > > > - Rha Diseno y Desarrollo (2 euro) > > > > > > :**Installation**: > > > > > > - See http://pythonide.stani.be/manual/html/manual2.html > > > > > > :**Development**: > > > > > > - http://developer.berlios.de/mail/?group_id=4161 > > > > > > About SPE: > > > SPE is a python IDE with auto-indentation, auto completion, call tips, > > > syntax coloring, uml viewer, syntax highlighting, class explorer, > > > source index, auto todo list, sticky notes, integrated pycrust shell, > > > python file browser, recent file browser, drag&drop, context help, ... > > > Special is its blender support with a blender 3d object browser and its > > > ability to run interactively inside blender. Spe integrates with XRCed > > > (gui > > > designer) and ships with wxGlade (gui designer), PyChecker (source > > > code doctor), Kiki (regular expression console) and WinPdb (remote, > > > multi-threaded debugger). > > > > > > The development of SPE is driven by its donations. Anyone who donates > > > can ask for an nice pdf version of the manual without ads (74 pages). From claureal81 at yahoo.it Sat Nov 18 06:22:13 2006 From: claureal81 at yahoo.it (Ciad) Date: 18 Nov 2006 03:22:13 -0800 Subject: MAKE GOOD MONEY BY INTERNET Message-ID: <1163848933.731124.307470@e3g2000cwe.googlegroups.com> You may have read these letters asking you to send $1 to 6 different addresses. Putting your home address on the internet can be risky, but through PayPal all you have to provide is your email address. Its safe and easy. Just go to use the link below and set up your account! I am not a gullible person and have never trusted things like this, but I gave it a try, hey its only $6, I figured at least 6 people would respond out of the millions of people that use the internet. Go to Paypal now and sign up for a free PREMIER or BUSINESS account, its easy to do (don't set up the PERSONAL ACCOUNT, with this one you can't receive more then 200$) . https://www.paypal.com/uk/mrb/pal=Q3WPRUS8V9LLE How it Works-- HOW TO TURN $6 INTO $6,000+!!! THIS REALLY CAN MAKE YOU EASY MONEY!! IT WORKS!!! BUT YOU HAVE TO FOLLOW IT TO THE LETTER FOR IT TO WORK!!!! A little while back, I was browsing through newsgroups, just like you are now and came across an article similar to this that said you could make thousands dollars within weeks with only an initial investment of $6.00! So I thought, "Yeah, right, this must be a scam," but like most of us, I was curious, so I kept reading. Anyway, it said that you send $1.00 through Paypal to each of the emails stated in the article. Then you place your own email address at the bottom of the list at #6. After that send the article to all your friends and relatives and post it in at least 200 news groups(There are thousand). No catch that was it. So after thinking it over, and talking to few people first, I thought about trying it. I figured what have I got to lose except $6.00, right? Like most of us I was a little skeptical and a little worried about the legal aspects of it: It follows the same regulations as the mailed "chain letters", which according to the U.S. Post Office (1-800-725-2161) is indeed legal! Then I invested the measly $6.00. Well GUESS WHAT!!?. Within 7 days, I started getting money in my paypal account! I was shocked! I figured it would end soon, but the money just kept coming in. In my first week, I made about $20.00. By the end second week I had made a total over $1,200.00! In the third week I had over $10,000.00 and it's still growing. This is now my fourth week and I have made a total of just over $36,000.00 and it's still coming in rapidly. It's certainly worth $6.00. Let me tell you how this works and most importantly, why it works? Also, make sure you print a copy of this article NOW, so you can refer to it as you need to. REQUIREMENTS: You must have a verified Premium or Business Paypal account. If you do not have an account you can use the link below and follow the instructions to set up a free account. In order to place the initial $6 into your account, you will have to verify your bank account with Paypal (which may take a few days). Paypal is 100% secure and is used by millions of people world wide. https://www.paypal.com/uk/mrb/pal=Q3WPRUS8V9LLE Directions STEP 1: Send, through Paypal, $1.00 to each email on the list below. Make the subject of the payment "Email List" and in the comments, write "PLEASE PUT ME ON YOUR EMAIL LIST."(Ensure in this page the 6 email addresses are completely shown because sometime some web provider hide part of these against the spammers. Usually you have just to click on the mail address for show it ). What you are doing is creating a service by this and best of all you are not giving your address to anyone you do not know. THIS IS ABSOLUTELY LEGAL! The email list: 1) scarlett85us at yahoo.com 2) jrmlcb at yahoo.com 3) rogerrd34 at aol.com 4) notesfordeb at hotmail.com 5) claureal81 at yahoo.it 6) pmlbianchi at yahoo.com STEP 2: Now take the #1 email off the list that you see above, move the other addresses up (6 becomes 5, 5 becomes 4, etc.) and add YOUR email address (the one used on the Paypal account) as number 6 on the list. STEP 3: Change anything you need to, but try to keep this article as close to original as possible. Now, send your amended article to all email address you have and post it in at least 200 newsgroups message board, Chat Rooms, Etc. (I think there are close to 32,000 groups) All you need is 200, but remember, the more you post, the more money you make - as well as everyone else on the list! DIRECTIONS--HOW TO POST TO NEWSGROUPS, MESSAGE BOARD Step 1: You do not need to re-type this entire letter to do your own posting. Simply select the text by putting your cursor at the top the document and dragging it to the bottom. Then you select copy from the edit menu. Step 2: Open a blank 'notepad' (or any word processor program) file and place your cursor at the top of the blank page. From the 'edit' menu select 'paste'. This will paste a copy of the letter into notepad so that you can add your name to the list. Step 3: Save your new notepad file as a .txt file. If you want to do your postings in different sittings, you'll always have this file to go back to. Step 4: Log on to your favorite search engine and search any of the following : on-line forums, message boards, chat sites, discussions. Just for example here are some search engines: yahoo.com, google.com, altavista.com, excite.com. You then search with the following subjects: millionaire message board, money making message board, employment message board, money making discussions, money making forum, business message board etc. You will find thousand & thousand message boards. Click one by one then you will find the option to post a new message. Step 5: Visit these message boards and post this article as a new message by highlighting the text of this letter and selecting paste from the edit menu. Fill in the Subject, this will be the header that everyone sees as they scroll through the list of postings in a particular group. Give your header a catchy phrase. Then click the post message button. You're done with your first one!. Congratulations! THAT'S IT! All you have to do is jump to different newsgroups and post away, after you get the hang of it, it will only take about 30 seconds for each newsgroup! REMEMBER, THE MORE NEWSGROUPS OR MESSAGE BOARDS YOU POST IN, THE MORE EMAILS YOU SEND, THE MORE MONEY YOU WILL MAKE!! BUT YOU HAVE TO POST A MINIMUM OF 200. That's it! You will begin receiving money within days! JUST MAKE SURE THE EMAIL YOU SUPPY IS EXACTLY AS IT APPEARS ON PAYPAL. Now the WHY part: Out of 200 postings, say I receive only 5 replies (a very low example). So then I Made $5.00 with my name at #6 on the letter. Now, each of the 5 persons who just sent me $1.00 make the MINIMUM 200 postings, each with my name at #5 and only 5 persons respond to each of the original 5, that is another $25.00 for me, now those 25 each make 200 MINIMUM posts with my name at #4 and only 5 replies each, I will bring in an additional: $125.00! Now, those 125 persons turn around and post the MINIMUM 200 with my name at #3 and only receive 5 replies each, I will make an additional $625.00! OK, now here is the fun part: Each of those 625 persons post a MINIMUM 200 posts with my name at #2 and they only receive 5 replies that just made me $3,125.00!!! Those 3,125 persons will all deliver this message to 200 newsgroups with my name at #1 and if still 5 persons per 200 newsgroups react I will receive $15,625.00! With an original investment of only $6.00! AMAZING! When your name is no longer on the list, you just take the latest posting in the newsgroups, and send out another $6.00 to names on the list, putting your name at number 6 again. And start posting again. The thing to remember is, do you realize that thousands of people all over the world are joining the internet and reading these articles everyday, JUST LIKE YOU are now!! So can you afford $6. And see if it really works?? I think so? People have said, 'What if the plan is played out and no one sends you: the money? So what are the chances of that happening when there are tons of new honest users and new honest people who are joining the internet and newsgroups everyday and are willing to give it a try? Estimates are at 20,000 to 50,000 new users, every day, with thousands of those joining the actual Internet. Remember, if everyone plays FAIRLY and HONESTLY this will work. Sincerely, J. R. M. L. C. R. From amichail at gmail.com Wed Nov 8 01:25:10 2006 From: amichail at gmail.com (Amir Michail) Date: 7 Nov 2006 22:25:10 -0800 Subject: unpickling Set as set Message-ID: <1162967110.642248.54400@m7g2000cwm.googlegroups.com> Hi, Is there an easy way to unpickle the older Set as the newer set behind the scenes when using shelve? Amir From mail at microcorp.co.za Thu Nov 2 02:23:56 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 2 Nov 2006 09:23:56 +0200 Subject: report progress from C function References: <1162336313.895048.202440@k70g2000cwa.googlegroups.com><20061101135354.39489.qmail@web88312.mail.re4.yahoo.com> Message-ID: <024201c6fe5f$dc0fa980$03000080@hendrik> "Fredrik Lundh" wrote: > Michael S wrote: > > > I downloaded Pyrex and ran it through their own > > example. The code looks quite messy, and I even saw a > > few "goto"s. > > looked at the assembler output from your C compiler lately? > > LOL! - is it even possible to code an if else without conditional jumps? - Hendrik From fredrik at pythonware.com Sat Nov 11 03:05:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Nov 2006 09:05:45 +0100 Subject: Tkinter: How do I change the actual width of a widget? In-Reply-To: <1163201725.520487.176030@i42g2000cwa.googlegroups.com> References: <1163201725.520487.176030@i42g2000cwa.googlegroups.com> Message-ID: Mudcat wrote: > I am trying to change the width of a widget based on pixel size and not > on characters. I can't figure out how to do this. > > Normally to change to the size of a widget it looks like: > > widget.configure(width = x) > > However that is in characters, not in pixels. To retrieve the actual > size of a widget, I believe it is done with: > > x = widget.winfo_width() > > Obviously that value can not be used in the configure statement. Is > there a way to dynamically change the width (and height) of a widget > using the winfo data? look for "pack_propagate" on this page for one way to do it: http://effbot.org/tkinterbook/button.htm From Roberto.Bonvallet at cern.ch Fri Nov 10 12:21:12 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Fri, 10 Nov 2006 17:21:12 +0000 (UTC) Subject: SyntaxError: Invalid Syntax. References: <1163178099.156160.29280@k70g2000cwa.googlegroups.com> <1163178336.281812.140580@f16g2000cwb.googlegroups.com> <1163178581.231837.18120@h48g2000cwc.googlegroups.com> Message-ID: ronrsr wrote: > thanks for the speedy answer. what i meant was: > > return MySQLdb.connect (host = "db91b.pair.com", > user = "homebase", > passwd = "Newspaper2", > db = "homebase_zingers" > ); > > > but even when I have that, I still get the same error. Could you please copy and paste the exact code that is triggering the error, and the exact error message? (BTW, in Python you don't need to end your statements with a semi-colon) -- Roberto Bonvallet From anthra.norell at vtxmail.ch Thu Nov 2 07:17:47 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Thu, 02 Nov 2006 13:17:47 +0100 Subject: unescape HTML entities In-Reply-To: References: <45449EAC.4070103@vtxmail.ch> Message-ID: <4549E1EB.1030205@vtxmail.ch> Rares Vernica wrote: > Hi, > > Nice module! > > I downloaded 2.3 and I started to play with it. The file names have > funny names, they are all caps, including extension. > > For example the main module file is "SE.PY". Is you try "import SE" it > will not work as Python expects the file extension to be "py". > > Thanks, > Ray > > Frederic Rentsch wrote: > >> Rares Vernica wrote: >> >>> Hi, >>> >>> How can I unescape HTML entities like " "? >>> >>> I know about xml.sax.saxutils.unescape() but it only deals with "&", >>> "<", and ">". >>> >>> Also, I know about htmlentitydefs.entitydefs, but not only this >>> dictionary is the opposite of what I need, it does not have " ". >>> >>> It has to be in python 2.4. >>> >>> Thanks a lot, >>> Ray >>> >>> >> One way is this: >> >> >>> import SE # >> Download from http://cheeseshop.python.org/pypi/SE/2.2%20beta >> >>> SE.SE ('HTM2ISO.se')('input_file_name', 'output_file_name') # >> HTM2ISO.se is included >> 'output_file_name' >> >> For repeated translations the SE object would be assigned to a variable: >> >> >>> HTM_Decoder = SE.SE ('HTM2ISO.se') >> >> SE objects take and return strings as well as file names which is useful >> for translating string variables, doing line-by-line translations and >> for interactive development or verification. A simple way to check a >> substitution set is to use its definitions as test data. The following >> is a section of the definition file HTM2ISO.se: >> >> test_string = ''' >> ø=(xf8) # 248 f8 >> ù=(xf9) # 249 f9 >> ú=(xfa) # 250 fa >> û=(xfb) # 251 fb >> ü=(xfc) # 252 fc >> ý=(xfd) # 253 fd >> þ=(xfe) # 254 fe >> é=(xe9) >> ê=(xea) >> ë=(xeb) >> ì=(xec) >> í=(xed) >> î=(xee) >> ï=(xef) >> ''' >> >> >>> print HTM_Decoder (test_string) >> >> ?=(xf8) # 248 f8 >> ?=(xf9) # 249 f9 >> ?=(xfa) # 250 fa >> ?=(xfb) # 251 fb >> ?=(xfc) # 252 fc >> ?=(xfd) # 253 fd >> ?=(xfe) # 254 fe >> ?=(xe9) >> ?=(xea) >> ?=(xeb) >> ?=(xec) >> ?=(xed) >> ?=(xee) >> ?=(xef) >> >> Another feature of SE is modularity. >> >> >>> strip_tags = ''' >> ~<(.|\x0a)*?>~=(9) # one tag to one tab >> ~~=(9) # one comment to one tab >> | # run >> "~\x0a[ \x09\x0d\x0a]*~=(x0a)" # delete empty lines >> ~\t+~=(32) # one or more tabs to one space >> ~\x20\t+~=(32) # one space and one or more tabs to >> one space >> ~\t+\x20~=(32) # one or more tab and one space to >> one space >> ''' >> >> >>> HTM_Stripper_Decoder = SE.SE (strip_tags + ' HTM2ISO.se ') # >> Order doesn't matter >> >> If you write 'strip_tags' to a file, say 'STRIP_TAGS.se' you'd name it >> together with HTM2ISO.se: >> >> >>> HTM_Stripper_Decoder = SE.SE ('STRIP_TAGS.se HTM2ISO.se') # >> Order doesn't matter >> >> Or, if you have two SE objects, one for stripping tags and one for >> decoding the ampersands, you can nest them like this: >> >> >>> test_string = "

> style='line-height:110%'>René est un garçon qui >> paraît plus âgé.

" >> >> >>> print Tag_Stripper (HTM_Decoder (test_string)) >> Ren? est un gar?on qui para?t plus ?g?. >> >> Nesting works with file names too, because file names are returned: >> >> >>> Tag_Stripper (HTM_Decoder ('input_file_name'), 'output_file_name') >> 'output_file_name' >> >> >> Frederic >> >> >> >> > > Arrrgh! Did it again capitalizing extensions. We had solved this problem and here we have it again. I am so sorry. Fortunately it isn't hard to solve, renaming the files once one identifies the problem, which you did. I shall change the upload within the next sixty seconds. Frederic I'm glad you find it useful. From steve at REMOVE.THIS.cybersource.com.au Sat Nov 11 08:39:44 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 12 Nov 2006 00:39:44 +1100 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> <4rjlkqFrlskqU1@mid.individual.net> <4rk5giFrerjfU1@mid.individual.net> Message-ID: On Sat, 11 Nov 2006 01:13:03 -0600, Ron Adam wrote: > Steven D'Aprano wrote: >> On Fri, 10 Nov 2006 21:24:50 +0100, Bjoern Schliessmann wrote: >> >>> Marc 'BlackJack' Rintsch wrote: >>> >>>> No it doesn't -- look again at the example given above. It's >>>> legal syntax in Python but doesn't have the semantics implied by >>>> the example. >>> Sorry, I don't understand -- what is the difference between the >>> example as it is and the implied semantics of it? >> >> Inform 6 "x == blue or red or yellow" is equivalent to the Python >> >> x == blue or x == red or x == yellow > > Maybe it should have been expressed as: > > x == (blue or red or yellow) But that has very different semantics still -- since parentheses have the highest priority, it means "evaluate (blue or red or yellow), then test if x is equal to the result". It might be useful on occasion to have a construct for "x equals blue or red or yellow" in the sense used by normal English or Inform 6. And, funnily enough, Python has such a construct. You just have to write "in" instead of ==, and use a tuple for the terms: x in (blue, red, yellow) Not hard to remember, and unambiguous. -- Steven. From jeremit0 at gmail.com Thu Nov 2 10:32:37 2006 From: jeremit0 at gmail.com (jeremito) Date: 2 Nov 2006 07:32:37 -0800 Subject: string formatter for tuple Message-ID: <1162481557.791817.41690@b28g2000cwb.googlegroups.com> I have the following in my code a = (1,2,3) print "a = %s" %a But when I run this, I get: TypeError: not all arguments converted during string formatting Now I realize why this happens, a is actually 3 elements when the print statement is only expecting to print one value. I tried print "a = %s" %(a) but I got the same error. How can I print a tuple with a single string format? Thanks, Jeremy From p.lavarre at ieee.org Fri Nov 10 00:25:24 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 9 Nov 2006 21:25:24 -0800 Subject: to Doctest as SystemExit is to Python Message-ID: <1163136324.202924.165630@k70g2000cwa.googlegroups.com> > From: http://docs.python.org/lib/doctest-soapbox.html ... > Regression testing is best confined to dedicated objects or files ... Can I somehow tell doctest that it's time to quit? I ask because not all doctest examples are created equal. Some failures are catastrophic, making all subsequent failures at least uninteresting, and maybe painfully slow. Other failures are negligible, making the print of any subsequent failure valuable. So sys.exit() doesn't do what I mean: it raises SystemExit, but doctest redefines the SystemExit exception to mean print a traceback, rather than meaning to exit quietly after a noisily catastrophic failure, exiting almost as if the doctest had passed. And doctest.REPORT_ONLY_FIRST_FAILURE doesn't do what I mean: it prints only the first failure, always, never the valuable subsequent failures. Can doctest somehow be persuaded to do the right thing? That is, to exit after a catastrophic failure, but not after a negligible failure, and not after an independent failure? In the last Python I shipped, to get the effect of exit after catastrophe, I actually faked a run of doctest: print 'Expected:' print " '...'" print 'Got:' print " " + repr(result) print '***Test Failed***' sys.exit(-1) Surely that's wrong? Somehow not idiomatic Python? Surely I can somehow tell doctest that my code has just realised, sorry, it is time to quit? Thanks in advance, Pat LaVarre From soring at gmail.com Sat Nov 4 20:30:42 2006 From: soring at gmail.com (soring at gmail.com) Date: 4 Nov 2006 17:30:42 -0800 Subject: WSDL? References: <454ba334$0$12110$88260bb3@free.teranews.com> <32822fe60611040558v511b7ce5v3062279228adcdd@mail.gmail.com> Message-ID: <1162690242.646530.23220@h54g2000cwb.googlegroups.com> CORBA may work fine in an intranet environment, where you can control the server and the client, but it clearly failed to be a popular choice on the internet: have you seen any company offering webservices with a CORBA interface?? The main 2 choices that companies offering webservices seem to have are REST (Yahoo, Amazon, Google) and SOAP (Amazon, Google). And no, SOAP is not a Microsoft thing anymore: it's a standard supported by a lot of large companies (and neither Amazon nor Google are Microsoft shops, as far as I know). The reason SOAP moved away from the pure RPC model is because it needed to support the more modern and flexible distributed computing paradigm which is "message based", not "RPC based". But yeah, I fully agree that SOAP is very complicated, and the support for it is pretty poor. Sorin Steve Holden wrote: > Jorge Vargas wrote: > > On 11/4/06, Marc 'BlackJack' Rintsch wrote: > > > >>In , Jorge Vargas > >>wrote: > >> > >> > >>>and please please don't go to corba we need to kill that. > >> > >>Have you real reasons or is this a religious thing? As I see it Corba is > >>much better supported by Python libs than SOAP is. > >> > > > > I see ZSI as a very good engine for SOAP as for xmlrpc it's "better" > > since you can interact with a browser and then you can even have json > > rpc. > > > > but yes ur right is mostly because of religious reasons :) > > > When SOAP can do everything that Corba can do, and as efficiently, it > might stand a chance of displacing it. I see SOAP as essentially an ugly > bloated NIH response of the Microsoft camp to an open specification that > achieved all its goals in an elegant way. And all to allow inappropriate > remote-method execution through port 80 to avoid the corporate firewall. > Which ultimately just made firewalling port 80 that much more difficult. > > Microsoft is a poor church, and very uncaring of its adherents. So take > your religious reasons and leave Corba alone until SOAP is an effective > competitor ;-) > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From vincent.arnoux at rfo.atmel.com Wed Nov 29 11:26:15 2006 From: vincent.arnoux at rfo.atmel.com (Vincent Arnoux) Date: Wed, 29 Nov 2006 17:26:15 +0100 Subject: Reading GDSII layouts In-Reply-To: <1164735963.999050.300530@45g2000cws.googlegroups.com> References: <1164735963.999050.300530@45g2000cws.googlegroups.com> Message-ID: <200611291726.15940.vincent.arnoux@rfo.atmel.com> Le mardi 28 novembre 2006 18:46, Jacob Rael a ?crit?: > Funny, I started writing one this past weekend as a learning exercise > (handling large files and start to use classes). If ipkiss does not > work out, let me know specifically what you need and maybe my hack will > work. > > jr Well, if you know how to extract cell names and references from a GDSII layout, that would be usefull. Perhaps can you send me your code if you don't mind and I will try to do something from it ? Vincent From tuomas.vesterinen at pp.inet.fi Sun Nov 5 14:35:58 2006 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Sun, 05 Nov 2006 19:35:58 GMT Subject: forwarding *arg parameter In-Reply-To: References: <6pn3h.125$7b6.98@read3.inet.fi> <2Fp3h.195$7b6.100@read3.inet.fi> Message-ID: Stargaming wrote: > Either you take one of the snippets here: > http://aspn.activestate.com/ASPN/search?query=flatten§ion=PYTHONCKBK&type=Subsection > > or just use arg[0] clever (as mentioned a few times in this thread). Thanks. My solution became: >>> def flattern(arg): ... result = [] ... for item in arg: ... if isinstance(item, (list, tuple)): ... result.extend(flattern(item)) ... else: ... result.append(item) ... return tuple(result) ... >>> def g(*arg): ... arg = flattern(arg) ... return arg ... >>> def f(*arg): ... return g(arg) ... >>> f('foo', 'bar') ('foo', 'bar') TV From rw at smsnet.pl Wed Nov 29 10:22:51 2006 From: rw at smsnet.pl (Rob Wolfe) Date: 29 Nov 2006 07:22:51 -0800 Subject: Detecting recursion loops In-Reply-To: References: Message-ID: <1164813771.171053.93190@j44g2000cwa.googlegroups.com> robert wrote: > My code does recursion loops through a couple of functions. Due to problematic I/O input this leads sometimes to "endless" recursions and after expensive I/O to the Python recursion exception. > What would be a good method to detect recursion loops and stop it by user-Exception (after N passes or some complex criteria) without passing a recursion counter parameter through all the funcs? What about `sys.setrecursionlimit`? http://docs.python.org/lib/module-sys.html -- HTH, Rob From larry.bates at websafe.com Mon Nov 6 17:10:20 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 06 Nov 2006 16:10:20 -0600 Subject: assigning values in __init__ In-Reply-To: <454faf57$0$12993$c3e8da3@news.astraweb.com> References: <454faf57$0$12993$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Let's say I'm making a game and I have this base class: > > class Character(object): > > def __init__(self, name, stats): > self.name = name > self.strength = stats[0] > self.dexterity = stats[1] > self.intelligence = stats[2] > self.luck = stats[3] > > Is this a good way to assign the values to the different attributes? > Should 'stats' be a list/tuple (like this), or should I do *stats instead? > > I'm trying to think ahead to when I might want to add new attributes, > and I want to make sure this doesn't get crazy with individual > parameters instead of just the one list. > > Or maybe there's some way to loop through two lists (the stats and the > attributes) and assign them that way? I was thinking of a nested for > statement but that didn't seem to work. Sounds like what you should be doing is something like keyword arguments instead. class Character(object): def __init__(self, name, **kwargs): self.name=name for key, value in kwargs.items(): setattr(self, key, value) z=Character('name', strength=10, dexterity=5, intelligence=3, luck=0) Now you can easily introduce new keyword arguments. -Larry From gagsl-py at yahoo.com.ar Wed Nov 15 20:53:18 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 15 Nov 2006 22:53:18 -0300 Subject: Python v PHP: fair comparison? In-Reply-To: <1a6e01c7091c$34212470$0301a8c0@tmesa.com> References: <455bad51$0$26230$426a74cc@news.free.fr> <1a6e01c7091c$34212470$0301a8c0@tmesa.com> Message-ID: <7.0.1.0.0.20061115224716.06181e58@yahoo.com.ar> At Wednesday 15/11/2006 22:11, bruce wrote: >interesting ongoing thread... > >i've seen a number of these over the years.. my language is better than your >language!! > >i'm sure this question on the php list would have findings/results that are >essentially opposite of what is being discussed here! Sure. But after you realize that a language is just a tool to complete a task, most of the discussions are meaningless. The original post didn't say "python is better than php", and I think the comparison is rather fair. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From assaflavie at gmail.com Wed Nov 1 08:28:20 2006 From: assaflavie at gmail.com (Assaf Lavie) Date: 1 Nov 2006 05:28:20 -0800 Subject: authenticated https post In-Reply-To: References: <1162385421.870142.8680@h48g2000cwc.googlegroups.com> Message-ID: <1162387700.222826.249960@f16g2000cwb.googlegroups.com> I think that library is obsolete. It uses http, instead of https. On Nov 1, 3:00 pm, Fredrik Lundh wrote: > assaf wrote: > > I'm trying to use Python to work with del.icio.us's API. > > Basically, I need to be able to do a simple https post, with > > username/password authentication. > > (For those interested, the del.icio.us API is here: > >http://del.icio.us/help/api/) > > > I can't for the life of me find a simple https example code that > > works... I'm working on Windows, btw, if that makes any difference.tried http://code.google.com/p/pydelicious/? > > (it's linked from the "useful things that other people have made" > section on del.icio.us' help page, just above the "developers" section > where you found that api link). > > From agriff at tin.it Tue Nov 7 03:06:24 2006 From: agriff at tin.it (Andrea Griffini) Date: Tue, 07 Nov 2006 09:06:24 +0100 Subject: Unicode/ascii encoding nightmare In-Reply-To: <1162854476.903789.5550@b28g2000cwb.googlegroups.com> References: <1162842650.780517.180360@b28g2000cwb.googlegroups.com> <1162846564.782883.259110@h54g2000cwb.googlegroups.com> <454fa3c9$0$13767$4fafbaef@reader3.news.tin.it> <1162854476.903789.5550@b28g2000cwb.googlegroups.com> Message-ID: <45503dab$0$13758$4fafbaef@reader3.news.tin.it> John Machin wrote: > Indeed yourself. What does the above mean ? > Have you ever considered reading posts in > chronological order, or reading all posts in a thread? I do no think people read posts in chronological order; it simply doesn't make sense. I also don't think many do read threads completely, but only until the issue is clear or boredom kicks in. Your nice "double whammy" post was enough to clarify what happened to the OP, I just wanted to make a bit more explicit what you meant; my poor english also made me understand that you were just "suspecting" such an error, so I verified and posted the result. That your "suspect" was a sarcastic remark could be clear only when reading the timewise "former" reply that however happened to be lower in the thread tree in my newsreader; fact that pushed it into the "not worth reading" area. > It might help > you avoid writing posts with non-zero information content. Why should I *avoid* writing posts with *non-zero* information content ? Double whammy on negation or still my poor english kicking in ? :-) Suppose you didn't post the double whammy message, and suppose someone else made it seven minutes later than your other post. I suppose that in this case the message would be a zero content noise (and not the precious pearl of wisdom it is because it comes from you). > Cheers, > John Andrea From fredrik at pythonware.com Sat Nov 18 05:37:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 18 Nov 2006 11:37:49 +0100 Subject: How can I speed this function up? In-Reply-To: <1163845246.702167.16380@h48g2000cwc.googlegroups.com> References: <1163845246.702167.16380@h48g2000cwc.googlegroups.com> Message-ID: nnorwitz at gmail.com wrote: > Generally, don't create objects, don't perform repeated operations. In > this case, batch up I/O. > >> def write_data1(out, data): >> for i in data: >> if i[0] is 'ELEMENT': >> out.write("%s %06d " % (i[0], i[1])) >> for j in i[2]: >> out.write("%d " % (j)) >> out.write("\n") > > def write_data1(out, data, map=map, str=str): > SPACE_JOIN = ' '.join > lines = [("ELEMENT %06d " % i1) + SPACE_JOIN(map(str, i2)) > for i0, i1, i2 in data if i0 == 'ELEMENT'] > out.write('\n'.join(lines)) > > While perhaps a bit obfuscated, it's a bit faster than the original. > Part of what makes this hard to read is the crappy variable names. I > didn't know what to call them. This version assumes that data will > always be a sequence of 3-element items. > > The original version took about 11.5 seconds, the version above takes > just over 5 seconds. footnote: your version doesn't print the final "\n". here's a variant that do, and leaves the batching to the I/O subsystem: def write_data3(out, data, map=map, str=str): SPACE_JOIN = ' '.join out.writelines( "ELEMENT %06d %s\n" % (i1, SPACE_JOIN(map(str, i2))) for i0, i1, i2 in data if i0 == 'ELEMENT' ) this runs exactly as fast as your example on my machine, but uses less memory. and if you, for benchmarking purposes, pass in a "sink" file object that ignores the data you pass it, it runs in no time at all ;-) From no-spam at no-spam-no-spam.invalid Fri Nov 24 09:45:53 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 24 Nov 2006 15:45:53 +0100 Subject: fast listdir & stat Message-ID: I want to get the files and sizes and times etc. stats of a dir fast. os.listdir & iterating with os.stat seems not to run at optimal speed for network folders. Is there a faster possibility? (both for Win & *nix ; best platform independent) Robert From jstroud at mbi.ucla.edu Tue Nov 21 19:33:00 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 22 Nov 2006 00:33:00 GMT Subject: Trying to understand Python objects In-Reply-To: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> Message-ID: <0VM8h.17686$B31.14012@newssvr27.news.prodigy.net> walterbyrd wrote: > Reading "Think Like a Computer Scientist" I am not sure I understand > the way it describes the way objects work with Python. > > 1) Can attributes can added just anywhere? I create an object called > point, then I can add attributes any time, and at any place in the > program? Not all objects behave this way. For example, incidences of the object class: py> j = object() py> j.att = 2 ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : 'object' object has no attribute 'att' Strangely enough, the exact rule is difficult to infer from the behavior of cPython: py> def doit(): ... pass ... py> doit.att = 2 py> doit.att 2 py> type(j) py> type(doit) Instances of your own classes and the classes you define yourself behave as you describe, though: py> class C: pass ... py> C.classatt = 2 py> C.classatt 2 py> c = C() py> c.instat = 5 py> c.instat 5 > 2) Are classes typically created like this: > > class Point: > pass Its better for classes to descend from object, actually: py> class Point(object): pass ... py> type(Point) py> type(C) 'type' type classes behave correctly with certain language features, such as properties. Last I checked 'classobj' classes do not. So new-style ('type' type) classes are preferred. > Then attributes are added at some other time? Yes. This goes for old (clasobj) and new style classes. > 3) What is with the __underscores__ ?? They are hard to look at, but they are meant to signify implementation specific attributes of objects and not interface specific attributes. But, in my opinion, a lot of python code, especially "higher-level" code blurs the distinction, so it becomes a little underscore heavy. > 4) Are parameters passed to an class definition? > > class Whatever(params): > pass No. This is done under the implementation specific method called "__init__". py> class D(object): ... def __init__(self, param1, param2): ... self.a = param1 ... self.b = param2 ... py> d = D(2,5) py> d.a 2 py> d.b 5 > I sort-of understand the way objects work with PHP. With PHP, the > classes are defined in one place - sort of like a function. To me, that > makes more sense. The difference (and I don't know PHP) is that many of the objects you create (classes and instances of those classes) are "mutable". Which means, of course that you can change them. I've found that good programming practice requires less of this mutability in general (i.e. adding attributes on the fly), but it is there if you need it. I think this flexibility is part the python philosophy, but I am not a python philosopher (nor was I meant to be). James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From deets at nospam.web.de Mon Nov 13 11:05:43 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 13 Nov 2006 17:05:43 +0100 Subject: Python development time is faster. References: <1163425734.640509.99420@m73g2000cwd.googlegroups.com> <1163433118.770742.262140@e3g2000cwe.googlegroups.com> Message-ID: <4rrjenFspqicU2@mid.uni-berlin.de> > Oh, the memories... I went down the same road about two years ago, > though I didn't know about PyLucene at the time and wrapped in jython > the parts of Lucene I used... never bothered to deal with java's > verbosity after that. It's a pity that jython resembles abandon-ware > these days, when jRuby showed up pretty recently and is gaining in > penetration with the java crowd. It will be a non-trivial loss for > python if it is left behind in the JVM world (at least if the latter is > not swallowed by the .NET dark forces, which doesn't seem to happen any > time soon ;-). I wouldn't consider jython abandonware. It is under active development, and I'm using a 2.2 alpha successful for quite a while now - which usually serves my needs. The problem is/was that new-style classes were a major hurdle to take, and this now seems to be conquered. So lets hope (or contribute code....:P) that jython will see a 2.4 version ASAP. diez From p.m.deandraderodrigues at gmail.com Wed Nov 8 10:38:03 2006 From: p.m.deandraderodrigues at gmail.com (Pedro Rodrigues) Date: Wed, 8 Nov 2006 16:38:03 +0100 Subject: Help solving Python 2.5 crash: The instruction "0x7c168f1d" referenced memory at "0x00000001c In-Reply-To: <5a00f6240611080650i78ee03eawf716e358ca221bab@mail.gmail.com> References: <5a00f6240611080650i78ee03eawf716e358ca221bab@mail.gmail.com> Message-ID: <26195e840611080738q17af56afn4a41a7a4940359db@mail.gmail.com> Hi Bugra, thanks for your reply. I did try the same code on a Windows 2000 system where I also installed and later removed Python 2.5. There, I obtained the same problem :( That's why I think it has to do with software. I've also searched on the internet and this problem seems to come up also with other sorts of applications. This lead me to think that there might be some inconsistency in the Registry of Windows or some files that have been left behind after uninstall. I've tried to address these two possibilities but so far I did not succeed :( pedro On 11/8/06, Bugra Cakir wrote: > > Hi, > > I have came across this like problem in my simulations also. But the case > is not for the program structure or > python version, the case is hardware :) . If you have time to try it on > some other machine than the current and > if the problem arises then there is something different! > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From E.Doxtator at gmail.com Wed Nov 15 18:08:10 2006 From: E.Doxtator at gmail.com (E.Doxtator at gmail.com) Date: 15 Nov 2006 15:08:10 -0800 Subject: pyRTF and Footers Message-ID: <1163632090.351315.19480@h48g2000cwc.googlegroups.com> Hi All I've been using the pyRTF module to generate some documents that I need for work. In general, the module is good, and pretty simple to use. However, I am running into a problem with footers that doesn't quite make sense to me. My question is this: Is it possible to change the text of a footer throughout an RTF document? The data that I am using to produce my document is organized in a simple header/detail relationship. The document I want to produce looks roughly like this: --------------------------- USER001 detail data line 1 detail data line 2 detail data line 3 page footer that says "USER001, plus some other information" **page break** USER002 detail data line 1 detail data line 2 detail data line 3 page footer that says "USER002, plus some other information" **page break** USERnnn detail data line 1 detail data line 2 detail data line 3 page footer that says "USERnnn, plus some other information" END OF DOCUMENT --------------------------- I've gotten everything the way I want, except for the footer. The footer appears on the first page, but not on any other page. The code that generates the footer is (apologies in advance for poor style): --------------------------- def MakeFooter(self, facilitatir, startDate, endDate, tuID): section = Section() self.doc.Sections.append( section ) p = Paragraph( "%s - %s (%s - %s)" % ( facilitator, tuID, startDate, endDate ), LINE ) p.append( 'Page', PAGE_NUMBER, ' of ', TOTAL_PAGES ) section.Footer.append( p ) --------------------------- The logic that calls MakeFooter is: --------------------------- tuDoc = MakeTUDoc() DR = Renderer() for i in range( start, end + 1 ): key = "Traininguser%03d" % ( i ) tuDoc.MakeFooter( facilitator, startDate, endDate, key ) tuDoc.MakeHeader( key, module ) < code to populate the document with detail data > DR.Write( tuDoc.doc, tuDoc.OpenFile( 'JUNK' ) ) print( 'DONE!' ) --------------------------- (Note: the MakeHeader() method doesn't put an actual RTF header in the document-- it just puts text in a Heading1 format into a section at the top of the page, before the detail data.) I had a look at the RTF 1.5 specification (http://www.biblioscope.com/rtf15_spec.htm), and regarding headers and footers and it's pretty thin. I didn't see anything in the specification regarding support for changing footer text throughout the document. Nothing in there that said I could do it, either. Any ideas, anyone? Thanks in advance. This is an extremely helpful discussion group. -Doc From gagsl-py at yahoo.com.ar Fri Nov 24 21:11:07 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 24 Nov 2006 23:11:07 -0300 Subject: windows background process In-Reply-To: <1164243932.585949.202250@b28g2000cwb.googlegroups.com> References: <1164241677.007294.122880@k70g2000cwa.googlegroups.com> <1164243932.585949.202250@b28g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061124230841.03446c88@yahoo.com.ar> At Wednesday 22/11/2006 22:05, Podi wrote: >Some update... > >I just found out that the following seems to work, > >import subprocess >subprocess.Popen(' myargs', executable='mycmd.exe') > >However, it does not work with "my path\\mycmd.exe" > >subprocess.Popen(' myargs', executable='"my path\\mycmd.exe"') # error Same as before, executable should be the first argument, so it's seldom used. Try subprocess.Popen((full_path_to_mycmd, full_path_to_mycmd, arg1, arg2)) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From Jack.Andrews at boeing.com Wed Nov 22 01:18:13 2006 From: Jack.Andrews at boeing.com (EXI-Andrews, Jack) Date: Wed, 22 Nov 2006 16:18:13 +1000 Subject: re.match -- not greedy? Message-ID: <750FA239330A7E4CA15D456F37DFF8AE02500B0C@XCH-AU-01.au.nos.boeing.com> >> I wrote: >> >>>>>> import re;re.match('(a+)(ab)','aaab').groups() >>> ('aa', 'ab') >>> >>> this is the sort of behaviour i'd expect from >>> '(a+?)(ab)' >>> >>> a+ should greedily consume a's at the expense of the string >>> not matching > > Fredrick wrote: > that's a misunderstanding of what a regular expression is, though: > conceptually, a RE describes a set of strings, and the RE engine is > designed to answer the question "does this string belong to this > set". if that's so, what is the point of +? and *? (?) seems to me it's a bit more pragmatic than pure set membership jack From wescpy at gmail.com Thu Nov 9 04:28:52 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 9 Nov 2006 01:28:52 -0800 Subject: ANN: BayPIGgies, Thu Nov 9 @ 7:30p, Air Traffic Control Message-ID: <78b3a9580611090128m2fb0279ai554c54a32d51a6a9@mail.gmail.com> the silicon valley-san francisco bay area python users group meets at the Googleplex once a month in mountain view, CA. more info and directions available at http://baypiggies.net ---------- Forwarded message ---------- From: Dennis Reinhardt Date: Nov 2, 2006 9:03 PM To: Python Thursday Nov. 9, 2006 7:30-8:50 p.m. Technical Program ------------------------------------ Title Python for Prototyping in Air Traffic Control Presenter Russ Paielli (NASA Ames Research) About the talk The talk will start with a high-level overview of the US air traffic control system, then it will focus on tactical (i.e., short range) conflict alerting and describe the prototype software that we are developing to replace the legacy software that currently performs that function. Examples of actual "operational errors" will be presented, and the alerting performance of our system will be tested and compared with the legacy system. The rationale for using Python for the prototype and its testing will be briefly discussed. 8:50 p.m-... Mapping and Random Access ------------------------------------------ Mapping Moderator Dennis Reinhardt (DAIR Computer Systems) Mapping is a rapid-fire audience announcement open to all of topic headings (one speaker at a time). Random Access session (everyone breaks up into self-organized small-group discussion) follows immediately after Mapping. From __peter__ at web.de Sun Nov 5 08:05:54 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 05 Nov 2006 14:05:54 +0100 Subject: finding the list of the matched strings References: <1162731282.327715.49800@f16g2000cwb.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > Hi, I have a list of strings. And I want to find the subset which > matches a particular regular expression. > > import re > ll = ('a', 'b', 's1', 's2', '3s') > p = re.compile('^s.*') > newList = filter(lambda s: p.match(s), ll) or newList = [s for s in ll if p.match(s)] > I suppose there should be simple function to do this in re module. Is > there any? No. Peter From irmen.NOSPAM at xs4all.nl Mon Nov 6 20:05:07 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 07 Nov 2006 02:05:07 +0100 Subject: Pyro stability In-Reply-To: <1162783631.291535.221530@f16g2000cwb.googlegroups.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <454dd84b$0$328$e4fe514c@news.xs4all.nl> <1162783631.291535.221530@f16g2000cwb.googlegroups.com> Message-ID: <454fdbc5$0$335$e4fe514c@news.xs4all.nl> writeson wrote: > Irmen, > > Thanks, you're very good about answering Pyro related questions! Well, I do have an advantage here, being Pyro's author... :) --Irmen From gagsl-py at yahoo.com.ar Thu Nov 9 22:48:35 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 10 Nov 2006 00:48:35 -0300 Subject: pack a three byte int In-Reply-To: <1163128122.036554.163610@f16g2000cwb.googlegroups.com> References: <1163027401.386603.263030@k70g2000cwa.googlegroups.com> <1163121855.884088.12970@h48g2000cwc.googlegroups.com> <1163128122.036554.163610@f16g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061110003949.0597b988@yahoo.com.ar> At Friday 10/11/2006 00:08, p.lavarre at ieee.org wrote: > > > >>> import binascii > > > >>> cdb = binascii.unhexlify('%02X%06X%02X%02X' % (0x08, > 0x12345, 0x80, 0)) > > > >>> binascii.hexlify(cdb) > > >'080123458000' > > > > The only problem I can see is that this code is endianness-dependent; > > the suggested versions using pack(">...") not. But this may not be of > > concern to you. > >Thanks for cautioning us. I suspect we agree: > >i) pack('>...') can't say three byte int. >ii) binascii.hexlify evals bytes in the order printed. >iii) %X prints the bytes of an int in big-endian order. >iv) struct.unpack '>' of struct.pack '<' flips the bytes of an int >v) struct.unpack '<' of struct.pack '>' flips the bytes of an int >vi) [::-1] flips a string of bytes. Yes to all. >In practice, all my lil-endian structs live by the C/Python-struct-pack >law requiring the byte size of a field to be a power of two, so I can >use Python-struct-pack to express them concisely. Only my big-endian >structs are old enough to violate that recently (since ~1972) >popularised convention, so only those do I construct with >binascii.unhexlify. So you would have no problems. I stand corrected: the code above will always generate big-endian numbers. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From ppgoogle at tberg.net Sun Nov 26 08:32:01 2006 From: ppgoogle at tberg.net (i) Date: 26 Nov 2006 05:32:01 -0800 Subject: Ruby/Python/REXX as a MUCK scripting language In-Reply-To: <2006112418112116807-zobeid@techiecom> References: <2006112418112116807-zobeid@techiecom> Message-ID: <1164547921.815762.114940@f16g2000cwb.googlegroups.com> Tony Belding skrev: > I'm interested in using an off-the-shelf interpreted language as a > user-accessible scripting language for a MUCK. I'm just not sure if I > can find one that does everything I need. The MUCK must be able to > call the interpreter and execute scripts with it, but the interpreter > must also be able to call functions in the MUCK code. And then there's > the security issue that really worries me. . . I have to be able to > limit what the interpreter can execute. I can't have my users running > scripts that access the console, access the filesystem or sockets > directly, or call libraries or other binaries outside the MUCK. > > Is this practical? I'm thinking of Ruby or Python for this, if they > can meet the requirements. > > I might even consider REXX. . . I remember ARexx from my Amiga days, > and how great it was for string manipulation and application scripting. > However. . . My immediate target platform, Mac OS X, comes with Ruby > and Python but not REXX, so that's a disadvantage. > > My final option would be to create my own language interpeter where I > have control over everything that happens. That is what MUCKs have > always done in the past. But the result was always quirky, limited > languages like MUF (Multi-User Forth) which really turn off a lot of > coders. Furthermore, I've never created a language before, and it > would be a lot of extra work for me. > > -- > Tony Belding, Hamilton Texas Regina REXX har a "restricted mode", but it doesn't allow external calls so this is probably not a solution for You. Nevertheless, here is an excerpt from the manual about that mode: "2.6.3Regina Restricted Mode Many language interpreters provide a mechanism where code executed within that interpreter is limited to affecting the environment of the interpreter and cannot change the external environment in which the interpreter runs. Restricted mode is used in situations where you need to guarantee that the author of a Rexx program is unable to affect the user's environment. Situations where a restricted mode is applicable include, using Regina as a database procedural language, or as a language plug-in for a Web browser. Features of Regina that are disabled in restricted mode are: ? LINEOUT, CHAROUT, POPEN, RXFUNCADD BIFs ? "OPEN WRITE", "OPEN BOTH" subcommands of STREAM BIF ? The "built-in" environments eg. SYSTEM, CMD or PATH of ADDRESS command ? Setting the value of a variable in the external environment with VALUE BIF. ? Calling external functions To run Regina in restricted mode, you can start the Regina interpreter from the command line with the '-r' switch, or when using the Rexx SAA API, or-ing RXRESTRICTED to the CallType parameter of RexxStart() function." Thomas Berg From fredrik at pythonware.com Thu Nov 16 02:50:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 08:50:52 +0100 Subject: Yield In-Reply-To: <1163659530.752607.120880@m73g2000cwd.googlegroups.com> References: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> <455b4f9f$1@usenet01.boi.hp.com> <1163659530.752607.120880@m73g2000cwd.googlegroups.com> Message-ID: olive wrote: >> http://docs.python.org/ref/yield.html > > This is a perfect example that demonstrate how the actual python is bad > and most of the time useless (at least for me). there's a place for (relatively) formal reference documentation, but it's hardly ever the right place to learn why things are there, or how they are supposed to be used. > We really need mor example ! > > I would like to thanks Fredrik for his contribution to improve that. thanks! (for the curious, my current plan is to use http://effbot.org/zone/idea-seealso.htm files to link from the official documentation to tutorials, example collections, and blog articles. I encourage content producers to start looking into generating such files for their document collections.) From bearophileHUGS at lycos.com Sat Nov 25 14:45:39 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 25 Nov 2006 11:45:39 -0800 Subject: Graph Data Structures In-Reply-To: <1164465588.399198.173830@f16g2000cwb.googlegroups.com> References: <1164465588.399198.173830@f16g2000cwb.googlegroups.com> Message-ID: <1164483939.464327.143450@f16g2000cwb.googlegroups.com> Szabolcs Nagy: > i haven't read your code, but there are many graph implementations in > python. > in case you haven't found these yet: > http://wiki.python.org/moin/PythonGraphApi > > if you only want to do some analysis i think you need this one (as it's > pretty complete and simple): > https://networkx.lanl.gov/ > > i also recommend Guido's essay to read: > http://www.python.org/doc/essays/graphs.html I can also suggest my one: http://sourceforge.net/projects/pynetwork/ And boost graph bindings for Python, quite fast: http://www.osl.iu.edu/~dgregor/bgl-python/ Bye, bearophile From darran at edmstudio.com Sat Nov 18 19:13:30 2006 From: darran at edmstudio.com (darran) Date: 18 Nov 2006 16:13:30 -0800 Subject: Finding skilled pythonistas for micro-jobs? Message-ID: <1163895209.986877.13820@f16g2000cwb.googlegroups.com> I'm a partner in a design and technology studio that creates large-scale interactive exhibits for museums. We are agile - by choice. For big 6-12 month projects, we try and secure exceptional python talent on contract. The python job board addresses this need. Every few weeks though I run up against a bite-sized programming problem begging to be farmed out by our small company. The tasks themselves span the gamut from data wrangling (format conversions) to SWIG wrappers to Twisted to pyOpenGL. Often the task is 1 or 2 days of work. Not really big enough to warrant a job search, a contract, or even someone's full-time attention. The type of problem that is perfectly suited to a CS student or daytime programmer looking to make some extra money. Presently, when one of these jobs pops up, I just add 8-16 hours to my work week - much to the dismay of my 3-year old daughter who'd rather I pay someone and go to the park. The nice thing though about our bite-sized jobs is that the goals are perfectly clear because we are religious in our use of unit testing and test-driven development. Any suggestions then for locating skilled Python/C++ programmers for these small (micro) jobs? Cheers, Darran. From nogradi at gmail.com Wed Nov 22 06:37:59 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 22 Nov 2006 12:37:59 +0100 Subject: text file parsing (awk -> python) Message-ID: <5f56302b0611220337j5aeef3afy59d34919d7e9064a@mail.gmail.com> Hi list, I have an awk program that parses a text file which I would like to rewrite in python. The text file has multi-line records separated by empty lines and each single-line field has two subfields: node 10 x -1 y 1 node 11 x -2 y 1 node 12 x -3 y 1 and this I would like to parse into a list of dictionaries like so: mydict[0] = { 'node':10, 'x':-1, 'y':1 } mydict[1] = { 'node':11, 'x':-2, 'y':1 } mydict[2] = { 'node':12, 'x':-3', 'y':1 } But the names of the fields (node, x, y) keeps changing from file to file, even their number is not fixed, sometimes it is (node, x, y, z). What would be the simples way to do this? From bignose+hates-spam at benfinney.id.au Wed Nov 22 18:12:22 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 23 Nov 2006 10:12:22 +1100 Subject: Trying to understand Python objects References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> <45643a6f$0$7761$426a74cc@news.free.fr> <1164206156.302934.183510@b28g2000cwb.googlegroups.com> Message-ID: <87y7q3uld5.fsf@benfinney.id.au> "walterbyrd" writes: > Is there some book, or other reference, that explains of this? I was > thinking about "Python for Dummies." The "Think like a Computer > Scientist" book, and "Dive into Python" book don't seem to explain > Python's object model clearly enough for me. The canonical introduction is the Python tutorial:: To get benefit from this, you should *work through* this document, not merely read it. Do each exercise and don't go on until you believe you understand what it's doing. -- \ "When I turned two I was really anxious, because I'd doubled my | `\ age in a year. I thought, if this keeps up, by the time I'm six | _o__) I'll be ninety." -- Steven Wright | Ben Finney From gagsl-py at yahoo.com.ar Tue Nov 21 19:28:00 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 21 Nov 2006 21:28:00 -0300 Subject: Trying to understand Python objects In-Reply-To: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> Message-ID: <7.0.1.0.0.20061121205307.058bd8f8@yahoo.com.ar> At Tuesday 21/11/2006 20:03, walterbyrd wrote: >1) Can attributes can added just anywhere? I create an object called >point, then I can add attributes any time, and at any place in the >program? For "normal" python objects, yes, you can add/delete any attribute, anytime, anywhere. There are hooks where you can actively deny attribute creation, or "freeze" the attribute list, but these are considered advanced usage. >2) Are classes typically created like this: > >class Point: > pass > >Then attributes are added at some other time? Not "typically"! Although you *can* do that, doesn't mean that you *must* do things that way. A 2D point might say: class Point2D(object): def __init__(self, x, y): self.x = x self.y = y def distance(self, other): return math.hypot(other.x-self.x, other.y-self.y) p0 = Point2D(3, 2) p1 = Point2D(0, 6) p0.distance(p1) # gives 5 >3) What is with the __underscores__ ?? Names that begin and end in __ are used by Python itself and have some "magic" attached sometimes. The most common is __init__ (used to initialize a new instance). __str__ by example, is used to get an object's textual representation suitable for printing. If you execute >>> print p0 using the example above, you'll get something like . Add the following to the Point2D class and you get a nice pair: def __str__(self): return '(%f, %f)' % (self.x, self.y) >4) Are parameters passed to an class definition? > >class Whatever(params): > pass If you see something like that, "params" are not parameters, but base classes. The Whatever class inherits all attributes and methods known to its bases, and may provide its own. >I sort-of understand the way objects work with PHP. With PHP, the >classes are defined in one place - sort of like a function. To me, that >makes more sense. Usually in Python you also define a class in only one place - you *can* modify it later, and that's a powerful feature, but certainly you don't have to! -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From jorge.vargas at gmail.com Sat Nov 4 10:36:44 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Sat, 4 Nov 2006 15:36:44 +0000 Subject: WSDL? In-Reply-To: References: <454ba334$0$12110$88260bb3@free.teranews.com> <32822fe60611040558v511b7ce5v3062279228adcdd@mail.gmail.com> Message-ID: <32822fe60611040736w501c03c0n2d9ee09966a0316c@mail.gmail.com> On 11/4/06, Steve Holden wrote: > Jorge Vargas wrote: > > On 11/4/06, Marc 'BlackJack' Rintsch wrote: > > > >>In , Jorge Vargas > >>wrote: > >> > >> > >>>and please please don't go to corba we need to kill that. > >> > >>Have you real reasons or is this a religious thing? As I see it Corba is > >>much better supported by Python libs than SOAP is. > >> > > > > I see ZSI as a very good engine for SOAP as for xmlrpc it's "better" > > since you can interact with a browser and then you can even have json > > rpc. > > > > but yes ur right is mostly because of religious reasons :) > > > When SOAP can do everything that Corba can do, and as efficiently, it > might stand a chance of displacing it. I see SOAP as essentially an ugly > bloated NIH response of the Microsoft camp to an open specification that > achieved all its goals in an elegant way. And all to allow inappropriate > remote-method execution through port 80 to avoid the corporate firewall. > Which ultimately just made firewalling port 80 that much more difficult. > I have to disagree WSDL is a great standard and SOAP is great for transfering data from point a to point b. and it's very usefull for giving an interface for people to use like all those web2.0 api's out there. I agree on setting a server on port 80 to be a problem but that's a deployment issue I have never set a SOAP server on port 80 myself. > Microsoft is a poor church, and very uncaring of its adherents. So take > your religious reasons and leave Corba alone until SOAP is an effective > competitor ;-) > I'm sorry it's probably that I have seen some many bad Corba implementations at work that I just hate them. I recently found out that gnome applets are implemented on top of Corba and I'm very impress. > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden > > -- > http://mail.python.org/mailman/listinfo/python-list > From ptmcg at austin.rr._bogus_.com Thu Nov 9 02:14:34 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 09 Nov 2006 07:14:34 GMT Subject: Question regarding lists and regex References: Message-ID: "Prabhu Gurumurthy" wrote in message news:mailman.1959.1163053812.11739.python-list at python.org... > Here is a simple program, which queries /var/log/daemon on my OpenBSD box > and gets the list of valid ntp peers. > > Questions: > what is the easiest way for me to create lists on the fly, by that I mean > like perl > > push my @foo, something_from_say_stderr. The reason is as you can ip = > [""] statement before the for loop, I want to avoid that and use list > within the second ip loop, where I extract the ip address. Am I confusing? > Typically, one initializes a list to be empty, that is [], not [""]. Python will not read your mind at append time and think "oh! we're appending to a list and we forgot to create one in the first place, let's make one now." I guess Perl allows this, but the clarity of including the initialization statement overrules the convenience of leaving it out. > regex: I presume this is rather a dumb question, anyways here it comes! as > you can see from my program, pattIp = r\d{1,3}\.... etc, is there any > other easy way to group the reptitions, instead of typing the same regex 4 > times. > Here's one way, tested at the Python command line: >>> print r'\.'.join( [r'\d{1,3}']*4 ) \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} This avoids the pattern duplication, but I think using join is much less easily recognized as a pattern for an IP address. > TIA > Prabhu > Some other comments/free advice: 1. I was curious about this line: pid = int(re.sub(r'\[|\]', "", pidMatch.group())) You already know pidMatch.group() is going to start with a '[', followed by an integer string, and end with a ']', otherwise it wouldn't have matched pidPatt. Instead of whacking this with another re-type call, how about just some simple string slicing: pid = pidMatch.group()[1:-1] 2. No real need to keep count of the found ip's, just use len(ip) to tell you how many entries there are in the list (especially once you convert to intializing with an empty list). 3. Similarly, you'll be able to remove the 'if len(x)' test when printing out the contents of the ip list if you init with [] instead of [""]. Also, the Python idiom for testing if x is the empty string is usually just 'if x', not 'if len(x)'. -- Paul From hannibal.holm at gmail.com Fri Nov 3 10:23:05 2006 From: hannibal.holm at gmail.com (hannibal.holm at gmail.com) Date: 3 Nov 2006 07:23:05 -0800 Subject: refcounting errors??? In-Reply-To: References: <1162491997.320068.243850@h48g2000cwc.googlegroups.com> Message-ID: <1162567385.273737.271200@k70g2000cwa.googlegroups.com> Bingo, that works. Thanks! Fredrik Lundh wrote: > hannibal.holm at gmail.com wrote: > > > > The invokation of the foo-function goes somewhere in the line of: > > > > PyObject *up = PyBool_FromLong(1L); > > if (! up) PyErr_Print(); > > > > PyObject *res = PyObject_CallFunction(action.u.button.u.s, > > "(NIH)", > > what happens if you use "(OIH)" instead ? > > From laurent.pointal at wanadoo.fr Wed Nov 15 15:22:55 2006 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Wed, 15 Nov 2006 21:22:55 +0100 Subject: Python-2.5.exe? References: Message-ID: <455b76ef$0$27377$ba4acef3@news.orange.fr> Andrew Burton wrote: > What Python is best for installing to a USB Drive? I've actually got > 2.5 on a drive, but I forget which installation package I used. Maybe this one ? http://www.voidspace.org.uk/python/movpy/ > It > seems to me that it was an EXE file, but I cannot seem to find one of > those today. > > Can the Python-2.5.msi installation files from python.org be installed > so as not to touch the registry, to make them portable? It seems movpy can install Python2.5 on an USB Key. A+ Laurent. From nick at craig-wood.com Tue Nov 28 09:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 28 Nov 2006 08:30:03 -0600 Subject: "fork and exit" needed? References: <8osmm21skionildtnme1j0nvqbla6oqk72@4ax.com> Message-ID: Dennis Lee Bieber wrote: > On Tue, 28 Nov 2006 04:30:09 -0600, Nick Craig-Wood > declaimed the following in comp.lang.python: > > > > > If you run this > > > > import os,sys,time > > print os.getpid() > > sys.stdout = open(os.devnull, 'w') > > time.sleep(60) > > > > It prints its pid. > > > I would hope so, as you performed the print BEFORE reassigning > stdout... That is what I intended. I wanted the pid to look in /proc//fd to see what file descriptors were really open. > import os,sys,time > print "pre:", os.getpid() > sys.stdout = open(os.devnull, 'w') > print "post:", os.getpid() > time.sleep(60) > > (Granted, I'm on WinXP; I also suspect the original stdout is still open > in the background, maybe dualled with stderr?) Yes that is the point - the original stdout is still open. I don't think this discussion is relevant to windows though - windows has its own way of making daemons. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From fredrik at pythonware.com Thu Nov 16 10:55:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 16:55:37 +0100 Subject: Will subprocess eventually deprecate popen2 ? References: Message-ID: Daniel Klein wrote: >I have a few Python programs that use popen2, and they work quite > nicely and dependably, so I don't really have any reason to change > them to use the new subprocess module...unless of course there any > future plans to deprecate popen2. definitely not in the 2.X series. as for 3.X, nobody knows -- but chances are that even if the low-level support for popen2 disapperas, Python will ship with a popen2 implementation that delegates to subprocess. or you can write such an adapter yourself, the day you'll find that you want to upgrade to a fancy new Python version that doesn't have it. it'll take you 30 seconds: http://docs.python.org/lib/node539.html From paul at boddie.org.uk Thu Nov 30 06:50:01 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 30 Nov 2006 03:50:01 -0800 Subject: why would anyone use python when java is there? References: <1164762232.220759.57160@h54g2000cwb.googlegroups.com> <1164764454.043697.125730@j72g2000cwa.googlegroups.com> <1164818505.696250.264070@h54g2000cwb.googlegroups.com> Message-ID: <1164887401.610800.190370@f1g2000cwa.googlegroups.com> Richie Hindle wrote: > [Adam] > > For the life of me I can't understand why he would troll > > comp.lang.python when comp.lang.lisp is there. > > +1 QOTW! Overruled! ;-) Mostly because comp.lang.lisp seems to have become a much better place to get quotes of the week about Python than comp.lang.python itself. If there was a meta-QOTW or something like that then perhaps a +1 would be deserved. :-) Paul From gabor at nekomancer.net Thu Nov 16 16:05:19 2006 From: gabor at nekomancer.net (gabor) Date: Thu, 16 Nov 2006 22:05:19 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? Message-ID: hi, from the documentation (http://docs.python.org/lib/os-file-dir.html) for os.listdir: "On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects." i'm on Unix. (linux, ubuntu edgy) so it seems that it does not always return unicode filenames. it seems that it tries to interpret the filenames using the filesystem's encoding, and if that fails, it simply returns the filename as byte-string. so you get back let's say an array of 21 filenames, from which 3 are byte-strings, and the rest unicode strings. after digging around, i found this in the source code: > #ifdef Py_USING_UNICODE > if (arg_is_unicode) { > PyObject *w; > > w = PyUnicode_FromEncodedObject(v, > Py_FileSystemDefaultEncoding, > "strict"); > if (w != NULL) { > Py_DECREF(v); > v = w; > } > else { > /* fall back to the original byte string, as > discussed in patch #683592 */ > PyErr_Clear(); > } > } > #endif so if the to-unicode-conversion fails, it falls back to the original byte-string. i went and have read the patch-discussion. and now i'm not sure what to do. i know that: 1. the documentation is completely wrong. it does not always return unicode filenames 2. it's true that the documentation does not specify what happens if the filename is not in the filesystem-encoding, but i simply expected that i get an Unicode-exception, as everywhere else. you see, exceptions are ok, i can deal with them. but this is just plain wrong. from now on, EVERYWHERE where i use os.listdir, i will have to go through all the filenames in it, and check if they are unicode-strings or not. so basically i'd like to ask here: am i reading something incorrectly? or am i using os.listdir the "wrong way"? how do other people deal with this? p.s: one additional note. if you code expects os.listdir to return unicode, that usually means that all your code uses unicode strings. which in turn means, that those filenames will somehow later interact with unicode strings. which means that that byte-string-filename will probably get auto-converted to unicode at a later point, and that auto-conversion will VERY probably fail, because the auto-convert only happens using 'ascii' as the encoding, and if it was not possible to decode the filename inside listdir, it's quite probable that it also will not work using 'ascii' as the charset. gabor From sjdevnull at yahoo.com Wed Nov 1 09:59:23 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 1 Nov 2006 06:59:23 -0800 Subject: best way to check if a file exists? In-Reply-To: References: <1162383348.925961.231160@h48g2000cwc.googlegroups.com> <1162390455.727684.118970@b28g2000cwb.googlegroups.com> Message-ID: <1162393163.497688.89240@m7g2000cwm.googlegroups.com> Ben Finney wrote: > "wittempj at hotmail.com" writes: > > > Ben Finney wrote: > > > "wittempj at hotmail.com" writes: > > > > You could try to read the file, if that fails it doesn't exist: > > > > > > Except that there are other conditions than "File doesn't exist" > > > that can cause an 'open' to fail. > > > > Ok, true. You can test explicit on non existence as follows, and then > > decide to open the file > > Or you can simply use 'os.path.exists', as has been suggested several > times in this thread. The O_CREAT|O_EXCL method pointed out elsethread is preferrable, checking with "exists" and then creating if it returns false is racey. From sven.dahlstrand at gmail.com Thu Nov 9 17:11:53 2006 From: sven.dahlstrand at gmail.com (Sven) Date: 9 Nov 2006 14:11:53 -0800 Subject: urlretrieve get file name Message-ID: <1163110313.580268.19660@h48g2000cwc.googlegroups.com> Hi guys and gals, I'm wrestling with the urlretrieve function in the urllib module. I want to download a file from a web server and save it locally with the same name. The problem is the URL - it's on the form http://www.page.com/?download=12345. It doesn't reveal the file name. Some hints to point me in the right direction are greatly appreciated. Sven From robert.kern at gmail.com Sat Nov 11 21:55:00 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 11 Nov 2006 20:55:00 -0600 Subject: reduce to be removed? In-Reply-To: <1163297976.786873.124350@m73g2000cwd.googlegroups.com> References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163288885.884417.218270@f16g2000cwb.googlegroups.com> <1163297976.786873.124350@m73g2000cwd.googlegroups.com> Message-ID: Dustan wrote: > Robert Kern wrote: >> Dustan wrote: >>> Fredrik Lundh wrote: >>>> if you care about writing robust code, why not just use a for-loop, >>>> and the list extend method? >>> Because I'm embedding this expression in a list comprehension (as I >>> stated in my original post), and last time I checked, it's not possible >>> to treat a for-loop as an expression (which is what a list >>> comprehension requires). >> As with all such things, you stick the implementation in a well-named function >> and simply call the function everywhere. The implementation never needs to be a >> one-liner expression. > > It's already in a function, but in order to convert the reduce function > into a for-loop that I can use as an expression, I would have to create > another independent function, which would make that code more cluttered > than it already is. > > Unless you're saying to perform the list comprehension manually. That > would be two for-loops I use in the list comprehension, plus another > one to take place of the reduce function. Sure, that spreads out each > individual step a little more, but it also makes it more difficult to > understand what the overall goal of the code is (I'm going for > readability as well as easy maintenance here). Let's just say that we disagree entirely on what constitutes readability and maintainability. -- 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 e0427417 at student.tuwien.ac.at Tue Nov 21 16:39:09 2006 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Tue, 21 Nov 2006 22:39:09 +0100 Subject: Note about getattr and '.' In-Reply-To: <1164144112.686480.60240@j44g2000cwa.googlegroups.com> References: <1164144112.686480.60240@j44g2000cwa.googlegroups.com> Message-ID: <45637197$0$12642$3b214f66@tunews.univie.ac.at> szport at gmail.com wrote: > There is an interesting skewness in python: > > class A(object): pass > >>>> a=A() >>>> setattr(a, '$foo', 17) >>>> getattr(a, '$foo') > 17 > > But I can't write >>>> a.'$foo' > Yes, this is known. I think IronPython uses a specialized dictionary for members, which prohibits malformed names. I don't know if there will be such a dictionary in any future CPython version. (Would be good.) panzi From arkanes at gmail.com Thu Nov 30 14:19:59 2006 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Nov 2006 13:19:59 -0600 Subject: Is there an easier way to express this list slicing? In-Reply-To: <456F2C1D.8070803@gmx.net> References: <1164913125.509492.54060@79g2000cws.googlegroups.com> <456F2C1D.8070803@gmx.net> Message-ID: <4866bea60611301119q76bd314cla30ade83bb414f9@mail.gmail.com> On 11/30/06, Thomas Ploch wrote: > John Henry schrieb: > > If I have a list of say, 10 elements and I need to slice it into > > irregular size list, I would have to create a bunch of temporary > > variables and then regroup them afterwords, like: > > > > # Just for illustration. Alist can be any existing 10 element list > > a_list=("",)*10 > > (a,b,c1,c2,c3,d1,d2,d3,d4,d5)=a_list > > alist=(a,) > > blist=(b,) > > clist=(c1,c2,c3) > > dlist=(d2,d3,d4,d5) > > > > That obviously work but do I *really* have to do that? > > > > BTW: I know you can do: > > alist=a_list[0] > > blist=a_list[1] > > clist=a_list[2:5] > > dlist=a_list[5:] > > > > but I don't see that it's any better. > > > > Can I say something to the effect of: > > > > (a,b,c[0:2],d[0:5])=a_list # Obviously this won't work > > > > ?? > > > > I am asking this because I have a section of code that contains *lots* > > of things like this. It makes the code very unreadable. > > > > Thanks, > > > > Nothing in your code actually __is__ a list. they are all tuples... > A list is: > aList = [a,b,c1,c2,c3,d1,d2,d3,d4,d5] > True but not relevant, really, he should have said "sequence". But more importantly, you don't show what you do with alist, blist,clist,dlist. Without knowing what the end result is, nobody is going to be able to help you eliminate the middle steps. > Thomas > -- > http://mail.python.org/mailman/listinfo/python-list > From john106henry at hotmail.com Fri Nov 17 14:47:12 2006 From: john106henry at hotmail.com (John Henry) Date: 17 Nov 2006 11:47:12 -0800 Subject: remove a list from a list In-Reply-To: References: <455E0046.1090005@tim.thechases.com> <455E0A20.9000509@tim.thechases.com> Message-ID: <1163792832.404528.187950@k70g2000cwa.googlegroups.com> from sets import Set as set # Python 2.3 b = list( set([i.upper() for i in b) - set([i.upper() for i in a] ) ) Rares Vernica wrote: > Yeah, I ended up doing a similar kind of loop. That is pretty messy. > > Is there any other way? > > Thanks, > Ray > > Tim Chase wrote: > >> That is a nice solution. > >> > >> But, how about modifying the list in place? > >> > >> That is, l would become ['c', 'D']. > >> > >>> >>> e = ['a', 'b', 'e'] > >>> >>> l = ['A', 'a', 'c', 'D', 'E'] > >>> >>> s = set(e) > >>> >>> [x for x in l if x.lower() not in s] > >>> ['c', 'D'] > > > > > > Well...changing the requirements midstream, eh? ;-) > > > > You can just change that last item to be a reassignment if "l" is > > all you care about: > > > > >>> l = [x for x in l ...] > > > > Things get a bit hairier if you *must* do it in-place. You'd > > have to do something like this (untested) > > > > for i in xrange(len(l), 0, -1): > > if l[i-1].lower() in s: > > del l[i-1] > > > > > > which should do the job. > > > > -tkc > > > > > > From m_tayseer82 at yahoo.com Wed Nov 8 15:15:52 2006 From: m_tayseer82 at yahoo.com (Mohammad Tayseer) Date: Wed, 8 Nov 2006 12:15:52 -0800 (PST) Subject: tkFileDialog In-Reply-To: <8094b1b60611081154g12d3d26et2eb59137226d56e2@mail.gmail.com> Message-ID: <1754.3926.qm@web31113.mail.mud.yahoo.com> use askopenfilename() instead of askopenfile() > ******************************************** > import tkFileDialog > file = tkFileDialog.askopenfile() > print file > ******************************************** --------------------------------- Access over 1 million songs - Yahoo! Music Unlimited. -------------- next part -------------- An HTML attachment was scrubbed... URL: From noah.rawlins at comcast.net Mon Nov 13 20:42:24 2006 From: noah.rawlins at comcast.net (Noah Rawlins) Date: Mon, 13 Nov 2006 20:42:24 -0500 Subject: Unpacking sequences and keywords in one function call In-Reply-To: <1163466377.919531.113560@h54g2000cwb.googlegroups.com> References: <1163466377.919531.113560@h54g2000cwb.googlegroups.com> Message-ID: ram wrote: > Stupid question #983098403: > > I can't seem to pass an unpacked sequence and keyword arguments to a > function at the same time. What am I doing wrong? > > def f(*args, **kw): > for a in args: > print 'arg:', a > for (k,v) in kw.iteritems(): > print k, '=', v > >>>> f(1,2) > arg: 1 > arg: 2 > >>>> f(*[1,2]) > arg: 1 > arg: 2 > >>>> f(1,2, a=1) > arg: 1 > arg: 2 > a = 1 > >>>> f(*[1,2], a=1) > File "", line 1 > f(*[1,2], a=1) > ^ > SyntaxError: invalid syntax > > Thanks, > Rick > I don't know if it's because there's some potential ambiguity (that I'm not seeing), but yeah, you just can't do that. This should work though... >>> f(*[1, 2], **{'a':1}) noah From rrr at ronadam.com Fri Nov 10 15:57:04 2006 From: rrr at ronadam.com (Ron Adam) Date: Fri, 10 Nov 2006 14:57:04 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: <4554D416.70408@hobbshouse.org> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <4554D416.70408@hobbshouse.org> Message-ID: Michael Hobbs wrote: > Ron Adam wrote: >> The faq also pointed out a technical reason for requiring the colon. It makes >> the underlying parser much easier to write and maintain. This shouldn't be >> taken to lightly in my opinion, because a simpler easer to maintain and more >> reliable python parser means development time can be spent improving the >> language in other areas instead of fixing parsing problems every time a new >> feature is added that might be used in a conditional expression. >> > Not to be too picky about it, but the FAQ was referring to editor > parsers, not the parser used by Python itself. The Python parser could > easily change its grammar to make the colon optional. Yes, hmm. I seem to remember (possibly falsely) of someone saying it did make pythons parser simpler. Oh well. Making it easier for third party tools and parser to parse is still worth while in my opinion. > I find the editor parsing excuse to be weak since most editors tend to > get hung up on Python code anyway, regardless of the colons. (Except for > the ones that are specifically written to support Python, or are > insanely programmable, like emacs.) In fact, I find that my editor > usually gets confused when it comes across colons in dictionary literals > or lambda expressions. If it just stuck to looking at the indentation, > instead of trying to play off syntax tricks, it would behave much better. My editor (GVIM) has the most trouble with long triple quoted strings. I could probably modify the script a bit and fix that though. I've never run into problems with colons. In another post on this thread you use an example of consistancy as a reason for not having the colon. But maybe sometimes there can be too much consistency, like when you want to differentiate something because they have different contextual meaning. xxx xxx: yyy yyy yyy yyy Here the colon indicates a difference or change in context. A test vs a procedure, or a grouping vs attributes, etc. I suppose you could also interpret it as meaning 'related to'. In a way this is carried over to dictionaries where a key is related to it's value. A range is related to the loop body, a test is related to the if body, etc... It is also an outline form that frequently used in written languages. Something python tries to do, is to be readable as if it were written in plain language where it is practical to do so. So the colon/outline form makes a certain sense in that case as well. Cheers, Ron From spe.stani.be at gmail.com Mon Nov 6 18:41:08 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 6 Nov 2006 15:41:08 -0800 Subject: SPE editor slow? In-Reply-To: <454fb79c$1@quokka.wn.com.au> References: <454e6f35@quokka.wn.com.au> <1162827834.032589.109470@b28g2000cwb.googlegroups.com> <454fb79c$1@quokka.wn.com.au> Message-ID: <1162856468.914437.124260@b28g2000cwb.googlegroups.com> timmy schreef: > SPE - Stani's Python Editor wrote: > > timmy schreef: > > > > > >>hello i've been using the SPE editor on a moderately large project and > >>it's constantly pausing during editing, like it's attempting to check > >>something as i edit. > >>as you can imagine a 4 second pause every few characters is EXTREMELY > >>annoying when you just want to get some work done. i really like SPE's > >>layout and features but if it's going to be dogshit slow all the time > >>i'll have to change. please help! > > > > > > SPE does error syntax checking which works fine for normal sized python > > files. With these settings you can speed up SPE for larger projects: > > 1. Edit>Preferences>Editor: Check realtime with "none" (default value: > > compiler) > > 2. Edit>Preferences>Editor: Update sidebar "when clicked" > > > > You can first try step 1, if you want SPE faster, use step 2 as well. > > > > Stani > > > > thanks stani i actually had an incling that 2. was the real problem. > i've got probably 200 or so clases in my project and it was pausing > mainly when it came to names of things or a . > i changed it to on clicked and it's fine now. > > it still does something else though that i'm at a loss to fix. when i > open a file or run a script is throws up errors saying "Failed to > display HTML document in ISO-8859-1 encoding" > > i guess thats a problem with those bottom info windows? The bottom info window is indeed a wxhtml window. Please check if this problem also occurs in the wxpython demo. If yes, report this on the wxpython-user mailing list, otherwise report to my gmail address. Stani Stani From paddy3118 at netscape.net Mon Nov 13 09:10:55 2006 From: paddy3118 at netscape.net (Paddy) Date: 13 Nov 2006 06:10:55 -0800 Subject: Python development time is faster. In-Reply-To: <1163425734.640509.99420@m73g2000cwd.googlegroups.com> References: <1163425734.640509.99420@m73g2000cwd.googlegroups.com> Message-ID: <1163427055.506643.126100@e3g2000cwe.googlegroups.com> Chris Brat wrote: > I've seen a few posts, columns and articles which state that one of the > advantages of Python is that code can be developed x times faster than > languages such as <>. > > Does anyone have any comments on that statement from personal > experience? > How is this comparison measured? > > > Thanks > Chris Here's a start: http://www.tcl.tk/doc/scripting.html Go Googling. There's a paper out their that compares error rates and time to program, lines of code, for several languages and is often cited in defence of scripting languages. (Scripting languages have however moved on and now like to be called dynamic languages). - Pad. From vd12005 at yahoo.fr Fri Nov 3 14:02:14 2006 From: vd12005 at yahoo.fr (vd12005 at yahoo.fr) Date: 3 Nov 2006 11:02:14 -0800 Subject: Sorted and reversed on huge dict ? Message-ID: <1162580533.981364.211860@h54g2000cwb.googlegroups.com> Hello, i would like to sort(ed) and reverse(d) the result of many huge dictionaries (a single dictionary will contain ~ 150000 entries). Keys are words, values are count (integer). i'm wondering if i can have a 10s of these in memory, or if i should proceed one after the other. but moreover i'm interested in saving theses as values, keys sorted and reversed (ie most frequent first), i can do it with sort from unix command but i wonder how i should do it with python to be memory friendly. can it be done by using : from itertools import izip pairs = izip(d.itervalues(), d.iterkeys()) for v, k in reversed(sorted(pairs)): print k, v or will it be the same as building the whole list ? From mohan.us2010 at gmail.com Mon Nov 6 10:19:31 2006 From: mohan.us2010 at gmail.com (mohan) Date: 6 Nov 2006 07:19:31 -0800 Subject: Learning Python In-Reply-To: <1162803632.788766.147590@e3g2000cwe.googlegroups.com> References: <1162803632.788766.147590@e3g2000cwe.googlegroups.com> Message-ID: <1162826371.841769.283770@f16g2000cwb.googlegroups.com> Hi Kaushal, Other than "Core Python" by Chun, also try "Python: How To Program" by Dietel & Dietel. It is one of the good books for bigginers. Good Luck, Mohan. On Nov 6, 10:00 am, "kaushal" wrote: > Hi > > How do i start Learning Python,is there any reference material which I > can refer since I dont have > any programming experience > > Thanks and Regards > > Kaushal From martin.witte at gmail.com Wed Nov 1 07:15:48 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 1 Nov 2006 04:15:48 -0800 Subject: best way to check if a file exists? In-Reply-To: References: Message-ID: <1162383348.925961.231160@h48g2000cwc.googlegroups.com> John Salerno wrote: > What is the best way to check if a file already exists in the current > directory? I saw os.path.isfile(), but I'm not sure if that does more > than what I need. > > I just want to check if a file of a certain name exists before the user > creates a new file of that name. > > Thanks. You could try to read the file, if that fails it doesn't exist: try: f = open('xxx') except IOError: f = open('xxx', 'w') print "file doesn't exist" print f From billjosephson at hotmail.com Thu Nov 9 10:23:41 2006 From: billjosephson at hotmail.com (BillJosephson) Date: 9 Nov 2006 07:23:41 -0800 Subject: Can not download plugins for jEdit (help!!) In-Reply-To: <1163078175.600579.22930@h54g2000cwb.googlegroups.com> References: <1163055167.418011.236870@h48g2000cwc.googlegroups.com> <1163066294.697993.148680@h48g2000cwc.googlegroups.com> <1163078175.600579.22930@h54g2000cwb.googlegroups.com> Message-ID: <1163085821.558812.321220@b28g2000cwb.googlegroups.com> Ant wrote: > > Vim, it can handle all the things.http://www.vim.org/ > > I'm not convinced of that quite yet. jEdit's syntax highlighting seems > more robust (see SocketServer.py in the standard library for an example > - vim gets the highlighting of the first doc-comment wrong). I've also > not found anything like jEdit's Console plugin for vim. It's > interactive. You can run the current buffer in the console window. The > console interacts with an error reporting pane which allows you to > click on the error and it will take you to the appropriate line in the > code that the stack trace indicates. > > The only thing I have found for vim (and it is specific to running > Python code) is the runscript.vim plugin, which merely allows you to > view the stdout from the script in a different buffer. It doesn't allow > you to interact (say you are writing a console based interactive > application for example) nor does it have all of those other features > I mentioned. > > I'm very interested in other people's vim setup for Python coding > however, as I do use vim more than Python these days, mainly because I > have to use it a great deal on headless servers (jEdit would be no good > here of course) and I got fed up with adding artefacts such as > extraneous i's, o's and :w's into my code when working with jEdit ;-) > And it starts faster of course. Ant: Great. Can you help me get it? Thanks. From johnjsal at NOSPAMgmail.com Wed Nov 8 10:53:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Nov 2006 10:53:21 -0500 Subject: sqlite query not working In-Reply-To: References: <4550f36e$0$8780$c3e8da3@news.astraweb.com> <4550f7a5$0$14445$c3e8da3@news.astraweb.com> <4550fa9f$0$17710$c3e8da3@news.astraweb.com> Message-ID: <4551fd65$0$7047$c3e8da3@news.astraweb.com> Dennis Lee Bieber wrote: > The other thing to consider is that, if you were testing using a > single cursor, and single session, the database would have shown you > uncommitted changes. It wouldn't have been until you closed the > cursor/connection without a commit that the DBMS would have tossed them > -- a select would still retrieve your uncommited changes during that > transaction. Good point, and I wouldn't be surprised if I had done that too! Working with databases in Python (as opposed to direct command line queries) is fairly new to me, so who knows what crazy things I tried to do. :) From spe.stani.be at gmail.com Mon Nov 6 10:43:54 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 6 Nov 2006 07:43:54 -0800 Subject: SPE editor slow? In-Reply-To: <454e6f35@quokka.wn.com.au> References: <454e6f35@quokka.wn.com.au> Message-ID: <1162827834.032589.109470@b28g2000cwb.googlegroups.com> timmy schreef: > hello i've been using the SPE editor on a moderately large project and > it's constantly pausing during editing, like it's attempting to check > something as i edit. > as you can imagine a 4 second pause every few characters is EXTREMELY > annoying when you just want to get some work done. i really like SPE's > layout and features but if it's going to be dogshit slow all the time > i'll have to change. please help! SPE does error syntax checking which works fine for normal sized python files. With these settings you can speed up SPE for larger projects: 1. Edit>Preferences>Editor: Check realtime with "none" (default value: compiler) 2. Edit>Preferences>Editor: Update sidebar "when clicked" You can first try step 1, if you want SPE faster, use step 2 as well. Stani From levub137 at wi.rr.com Sun Nov 19 12:50:25 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 19 Nov 2006 17:50:25 GMT Subject: [ANN] rpncalc-2.5 RPN Calculator for Python Message-ID: The rpncalc package adds an interactive Reverse Polish Notation (RPN) interpreter to Python. This interpreter allows the use of Python as an RPN calculator. You can easily switch between the RPN interpreter and the standard Python interpreter. Home page: http://calcrpnpy.sourceforge.net/ Changes in 2.5 * Update the included clnum package. * Added ratapx and unique_roots commands. From pierre at saiph.com Sun Nov 19 13:14:54 2006 From: pierre at saiph.com (Imbaud Pierre) Date: Sun, 19 Nov 2006 19:14:54 +0100 Subject: tempfile.NamedTemporaryFile wont work In-Reply-To: References: <456049ca$0$4692$426a74cc@news.free.fr> Message-ID: <45609f0a$0$11670$426a74cc@news.free.fr> Peter Otten a ?crit : > Steven D'Aprano wrote: > > >>On Sun, 19 Nov 2006 13:11:13 +0100, Imbaud Pierre wrote: >> >> >>>On suse 9.3, tempfile.NamedTemporaryFile() doesnt work as expected. >> >>[snip] >> >> >>>Symptom: the file does not always exist, after the call to >>>NamedTemporaryFile(). Or at least its not seen by the strings command, >>>or by os.path.exists. >>> >>>I guess the bug is pretty much os dependent, or even filesystem >>>dependent (Im on reiserfs). Maybe the os is buggy, maybe, somehow, the >>>python interface. Or did I miss something? >>>Shame, I didnt even try to check for a python bug tracker. >> >>I can verify this problem occurs on Fedora Core 5 too: >> >>import os >>import sys >>import tempfile >>import subprocess >>def test(n): >>chunk = ': +++ abcd +++' >>for i in xrange(n): >>tf = tempfile.NamedTemporaryFile() >>tfName = tf.name >>tf.seek(0) >>tf.write(str(i) + chunk) >> tf.flush() >>if not os.path.exists(tfName): >>print 'pre-check: %s not there' % tfName >>subprocess.Popen(['strings', tfName]) >>if not os.path.exists(tfName): >>print 'post-check: %s not there' % tfName >> >> >>And here is a typical run, with the boring bits removed for ease of >>reading: >> >> >>>>>test(30) >> >>0: +++ abcd +++ >>1: +++ abcd +++ >> [ more of the same ] >>14: +++ abcd +++ >>strings: '/tmp/tmpOALbx9': No such file >>16: +++ abcd +++ >>17: +++ abcd +++ >>18: +++ abcd +++ >> [ more of the same ] >>27: +++ abcd +++ >>strings: /tmp/tmpdc52Nz: No such file or directory >>29: +++ abcd +++ >> >> >>Curiouser and curiouser... not only does os.path.exist always report the >>temp file as existing (at least in my tests), even when strings can't find >>it, but strings returns different error messages. >> >>Is it possible this is a bug in strings? > > > What /you/ are seeing is not a bug, I think. Popen() is asynchronous, > therefore you may enter the second iteration -- which implicitly closes the > temporary file -- before strings actually tries to access it. Use call() > and everything should be fine. Thanks A LOT, works fine, I feel kind of silly; your diagnostic is pretty obvious, afterward... I felt uneasy not closing the Popen, but it worked, so why bother? Its so easy to make ugly code! From frank at chagford.com Sat Nov 11 03:25:46 2006 From: frank at chagford.com (Frank Millman) Date: 11 Nov 2006 00:25:46 -0800 Subject: Inheritance Question In-Reply-To: References: <1163226712.585220.53550@f16g2000cwb.googlegroups.com> Message-ID: <1163233546.838226.187290@m73g2000cwd.googlegroups.com> Gabriel Genellina wrote: > At Saturday 11/11/2006 03:31, Frank Millman wrote: > > >Continuing your analogy of animals, assume a class A with a 'walk' > >method and an 'eat' method. > > > >Most animals walk the same way, but a few don't, so I create a subclass > >AW and override the walk method. > > > >Most animals eat the same way, but a few don't, so I create a subclass > >AE and override the eat method. > > > >How do I create an instance of an animal that both walks and eats > >differently? > > [snip] > Answer 1) Move *both* ways of walk, and *both* ways of eating, to > another base class. Best when this is pure behavior - no new > attributes are involved. > [snip details] > > Answer 2) Use an instance of another class to define how to walk and > how to eat. Advantage: it can later be modified at runtime (strategy pattern). > [snip details] Many thanks for this, Gabriel. I have seen explanations like this before, but my eyes usually glaze over before I have finished, and I end up more confused than when I started. With a combination of my subconscious slowly getting an understanding of this, and your clear explanation, I think I have finally got it. Obviously my real world situation is quite a bit more complex than this simple example, but with the help you have given me I can now experiment with different ideas and decide on the best strategy. Thanks again Frank From seymour.morris at gmail.com Sat Nov 18 20:57:29 2006 From: seymour.morris at gmail.com (Seymour) Date: 18 Nov 2006 17:57:29 -0800 Subject: Reloading after from adder import * ???? Message-ID: <1163901449.418534.251060@b28g2000cwb.googlegroups.com> I created a module with the DictAdder subclass as follows: class DictAdder(Adder): def add(self, x, y): new={} for k in x.keys(): new[k]=x[k] for k in y.keys(): new[k]=y[k] return new At the interactive prompt I then said: from Adder import * After defining an instance of DictAdder as x=DictAdder() and trying to add two dictionaries, I notice a typo in DictAdder. If I then go back and make a change to the DictAdder subclass I have to go through many steps to add two dictionaries (get the revision into active memory): 1. import Adder 2. Reload(Adder) 3. from Adder import * 4. x=DictAdder() Question: Is there an easier and quicker way to get DictAdder into active memory????? Thanks, Seymour From antroy at gmail.com Wed Nov 8 12:30:18 2006 From: antroy at gmail.com (Ant) Date: 8 Nov 2006 09:30:18 -0800 Subject: Exception Handling in TCPServer (was; Problem exiting application in Windows Console.) In-Reply-To: <1163001245.707034.310900@f16g2000cwb.googlegroups.com> References: <1162987854.490880.46820@h54g2000cwb.googlegroups.com> <1163001245.707034.310900@f16g2000cwb.googlegroups.com> Message-ID: <1163007018.221972.93580@b28g2000cwb.googlegroups.com> Ant wrote: ... > OK, I've narrowed the problem back to the way HTTPServer (actually its > TCPServer parent) handles exceptions thrown by the process_request > method by catching them all, and then calling a handle_error method. > There doesn't seem to be a way of getting at the exception thrown > however - does anyone know how I can get this information? Hmm. Lonely topic ;-) I've found a way to solve the problem, by creating a subclass of HTTPServer which overrides the handle_error method: class HelpServer(HTTPServer): def handle_error(self, request, client_address): exception_line = inspect.trace()[-1][-2][0] if "sys.exit" in exception_line: print "Trying to exit again!" sys.exit(0) else: HTTPServer.handle_error(self, request, client_address) This seems a really nasty hack though - any ideas for a cleaner way to do it? From aisaac at american.edu Fri Nov 10 12:11:24 2006 From: aisaac at american.edu (Alan G Isaac) Date: Fri, 10 Nov 2006 17:11:24 GMT Subject: handling many default values Message-ID: My class MyClass reuses many default parameters with a small number of changes in each instance. For various reasons I decided to put all the parameters in a separate Params class, instances of which reset the default values based on keyword arguments, like this: class Params: def __init__(self,**kwargs): #set lots of default values ... #set the deviations from defaults self.__dict__.update(kwargs) Is this a reasonable approach overall? (Including the last line.) Thanks, Alan Isaac From robert.kern at gmail.com Thu Nov 16 16:36:01 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 16 Nov 2006 15:36:01 -0600 Subject: accessing fortran modules from python In-Reply-To: <1163696370.036741.274000@b28g2000cwb.googlegroups.com> References: <1163696370.036741.274000@b28g2000cwb.googlegroups.com> Message-ID: sam wrote: > hello all, > > i am currently in the process of planning a piece of software to model > polymerisation kinetics, and intend to use python for all the > high-level stuff. the number-crunching is something i would prefer to > do in fortran (which i have never used, but will learn), but i have no > experience of accessing non-python code from python. i am also fairly > new to programming period, and am therefore tackling a fairly serious > issue reletive to my experience. > > how easy is it to get fortran modules running from python? if c is > easier to use in this respect, i could go in that direction instead. > > i realize there is a lot of material on this subject already available, > but i am finding it difficult to make sense of, it's like trying to > take a drink from a fire hose. > > any advice would be gratefully received. i will almost certainly be > coding this on windows, for what it's worth. > > thank you, > > sam > > PS if numpy is adequate for this, i would be quite happy to use it. i > got the impression it was more for matrix algebra. i will be > programming a monte carlo simulation, which will need to perform a lot > (a lot!) of simple operations over and over... numpy isn't for matrix algebra, specifically. It is primarily designed for operations on arrays. If your simple operations can be "vectorized," then numpy will benefit you. If you can describe your needs in more detail, we'll be happy to give you suggestions on the numpy-discussion list. http://www.scipy.org/Mailing_Lists Of course, since the major player in wrapping Fortran libraries for Python is f2py, a component of numpy, you're probably going to end up installing numpy anyways. http://numpy.scipy.org All of the f2py documentation is currently in the source, so start here: http://projects.scipy.org/scipy/numpy/browser/trunk/numpy/f2py/docs/README.txt Using f2py to wrap Fortran subroutines is actually a fair bit simpler than wrapping C code, mostly because typical Fortran uses a limited set of simple types. -- 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 bj_666 at gmx.net Fri Nov 10 12:14:02 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 10 Nov 2006 18:14:02 +0100 Subject: newbee I have an object how to check what's his class? References: <1163171613.040825.78290@m73g2000cwd.googlegroups.com> Message-ID: In , consternation wrote: > Thank You for reply but .... > I found solution suggested by You in a tutorial yesterday. For some reason > it doesn't work in my case. > > code: > #mem-dictionary in Y class for storing objects > #Y doesn't inherit from X > for (i,v) in self.mem.items(): > print " isinstance(x,X)" > print isinstance(v,X) > print "type(x) is X" > print type(v) is X > print v.__class__.__name__ > print v.__class__ > > result: > isinstance(x,X) > False > type(x) is X > False > > list Define "doesn't work". Obviously lists are not instances of your `X` class. So where's the problem? What did you expect and why? Ciao, Marc 'BlackJack' Rintsch From Eric_Dexter at msn.com Wed Nov 1 20:37:57 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 1 Nov 2006 17:37:57 -0800 Subject: trying to call main function with execfile with two arguments Message-ID: <1162431477.292694.201900@h54g2000cwb.googlegroups.com> I was trying to find out what my value for filename is but it will not print. The file I am calling csoundgrid2.main seems to work fine when I call it directly from spe with two values and I have used this file dialog to load other files the error I am getting is. thanks for any help in advance File "C:\Python24\Lib\site-packages\boa-constructor\test of snake\csoundgrid2.py", line 35, in loadFile infile = open(sys.argv[1], 'r') #The first argument passed in is the file name IndexError: list index out of range def sco_editor(self): "Pick a sco file and load it into a sco editor" dlg = wx.FileDialog(self,"load sco file", ".", "", "*.sco", wx.OPEN) try: if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() # Your code print filename csoundgrid2.main(filename, """;""") #("csoundgrid2.py", filename ,""";""", shell=True) #os.startfile('csoundgrid2.py', filename, """;""") finally: dlg.Destroy() https://sourceforge.net/project/showfiles.php?group_id=156455 http://www.dexrow.com From john106henry at hotmail.com Thu Nov 16 16:46:13 2006 From: john106henry at hotmail.com (John Henry) Date: 16 Nov 2006 13:46:13 -0800 Subject: About alternatives to Matlab In-Reply-To: <1163711343.870829.110030@h48g2000cwc.googlegroups.com> References: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> <1163711343.870829.110030@h48g2000cwc.googlegroups.com> Message-ID: <1163713573.147702.229320@k70g2000cwa.googlegroups.com> Bill Gates will have you jailed! :-) On a more serious note, is there any alternative to Simulink though? sturlamolden wrote: >and is infinitely > more expensive. > > Does anyone wonder why I am not paying for Matlab maintenance anymore? > > Sorry Mathworks, I have used your product for years, but you cannot > compete with NumPy. > > > Cheers, > Sturla Molden From nospam at domain.tld Thu Nov 9 00:37:59 2006 From: nospam at domain.tld (Stephan Kuhagen) Date: Thu, 09 Nov 2006 06:37:59 +0100 Subject: Cactching Stdout References: <1162976981.747479.226680@m7g2000cwm.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: >> popen...is this what I need? How can I use them? It is very important >> for me that I could take the output in real-time. >> Thanks for the help! >> Massi > > That's going to be difficult... popen and pipes work when one > process starts another INDEPENDENT process. I'm not sure, if it fits the problem, but just a few days ago I had the problem to catch the stdout and stderr of a module to process it before writing it to the console. What I did was basically this: --- import sys import StringIO # save the original streams _stdout_ = sys.stdout _stderr_ = sys.stderr # create StringIO string buffers to replace streams sys.stdout = StringIO.StringIO() sys.stderr = StringIO.StringIO() # Now print something, this goes to the string buffers instead of console print "Hello World to stdout" sys.stderr.write("Hello World to stderr\n") # Now process the contents of the buffers... ... # ...and print them to the real console afterwards _stdout_.write(sys.stdout) _stderr_.write(sys.stderr) # Clean up the string buffers for the next IO sys.stdout.truncate(0) sys.stderr.truncate(0) --- Of course you should put all that into defs and create own write/print functions to encapsulate the whole buffering/processing/cleanup. This works great for scripting, but I'm pretty sure, that it does not work for C Libraries in Python. But I do not know, how Python handles its streams internally, so it might be worth a try. Regards Stephan From no-spam at no-spam-no-spam.invalid Fri Nov 3 09:11:30 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 03 Nov 2006 15:11:30 +0100 Subject: Keyboard interrupts, Idle vs. SciTE In-Reply-To: <1162504504.220386.127570@h54g2000cwb.googlegroups.com> References: <1162504504.220386.127570@h54g2000cwb.googlegroups.com> Message-ID: John Ladasky wrote: > Hi there. > > The following minimal code in Python 2.3.4 works under Idle v. 1.0.3, > but not under SciTE v. 1.66: > > from time import sleep > try: > while True: > sleep(0.25) > print ".", > except KeyboardInterrupt: > print "\nKeyboard interrupt received. Exiting program.\n\n" > > > Under SciTE, I do not get my "exiting program" message. Instead, I get > the standard SciTE abort message: > > >> Process failed to respond; forcing abrupt termination... >> Exit code: 1 > > > I much prefer the SciTE environment to Idle. Is there any way that I > can rewrite my program to restore the keyboard interrupt function under > SciTE? Alternately, is there some setting that I can change in SciTE > to accomplish the same effect? Use PythonWin on Windows. It is based on the same Scintilla editor, but provides real interaction and inline script execution capabs, debugging ... SciTE catches only stdout ( sometimes :-) ) etc. robert From apardon at forel.vub.ac.be Fri Nov 10 14:07:04 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Nov 2006 19:07:04 GMT Subject: range syntax References: Message-ID: On 2006-11-10, Roberto Bonvallet wrote: > Colin J. Williams wrote: >> One of the little irritants of Python is that the range syntax is rather >> long-winded: >> [Dbg]>>> range(3, 20, 6) >> [3, 9, 15] >> [Dbg]>>> >> It would be nice if one could have something like 3:20:6. > > In that case, how would the parser know which colon terminates the > 'for' in the following example: > > for i in 2:3:4: > ... By the programmer using parenthesis. Like for i in (2:3): ... Just as you are supposed to use parthesis if you want a tuple as a function argument although normally a comma is enough to form a tuple. -- Antoon Pardon From john106henry at hotmail.com Fri Nov 10 01:48:10 2006 From: john106henry at hotmail.com (John Henry) Date: 9 Nov 2006 22:48:10 -0800 Subject: How to choose the right GUI toolkit ? In-Reply-To: <1163139352.206221.213180@m73g2000cwd.googlegroups.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163015347.164393.74110@i42g2000cwa.googlegroups.com> <6ov7l2lb9ip2u5jmd54e2kso1s78fc68bb@4ax.com> <1163139352.206221.213180@m73g2000cwd.googlegroups.com> Message-ID: <1163141290.868726.11330@h48g2000cwc.googlegroups.com> Upon closer look, the walkthrough did say: *************************** from PythonCard import model Change that so it says: from PythonCard import dialog, model Save the code. *************************** So, it works. John Henry wrote: > Bill Maxwell wrote: > > On 8 Nov 2006 11:49:07 -0800, "John Henry" > > wrote: > > > > > > > >John Salerno wrote: > > >> Dan Lenski wrote: > > >> > > >> > So, is there another toolkit I should be looking at? > > >> > > >> I highly recommend wxPython. It's very mature, full-featured, and > > >> portable, and fairly easy to learn as well. I can't really compare it to > > >> other toolkits (not having used any of them, except Tkinter), but it's > > >> definitely one of the most popular and well-supported ones out there. > > >> > > >> http://www.wxpython.org/ > > > > > >I highly recommend that you try PythonCard (which sits on top of > > >wxPython). You can get productive very very quickly. Take a look at: > > > > > >http://pythoncard.sourceforge.net/walkthrough1.html > > > > > > I took a brief look at PythonCard almost a year ago and got discouraged > > by what I found, so I stopped looking at it. I've inserted my notes > > from back then, below. Does anybody know if these things have been > > fixed in the latest release? > > > > Bill > > > > > > ===================================================================== > > My notes from Fri Dec-23-2005: > > > > This is a list of gripes I have while trying to learn about PythonCard. > > I'm trying to investigate various GUI builders for Python, and > > PythonCard looks promising, but a lot of things are getting in the way. > > > > I installed yesterday, using this installer: > > PythonCard-0.8.1.FIXED.win32.exe > > > > A) The very first example in the tutorial is wrong! > > > > On this page: http://pythoncard.sourceforge.net/documentation.html > > When you follow this link to try something for the very first time: > > > > Getting Started in PythonCard by Dan Shafer: > > http://pythoncard.sourceforge.net/walkthrough1.html > > > > You quickly see that the minimal.py example doesn't even contain > > this line, even though the tutorial refers to it: > > > > I am not sure which one you are referring to but in the > PythonCard\samples\minimal, you will find a minimal.py that says: > > #!/usr/bin/python > > """ > __version__ = "$Revision: 1.8 $" > __date__ = "$Date: 2005/12/17 15:20:02 $" > """ > > from PythonCard import model > > > class Minimal(model.Background): > def on_menuFileAbout_select(self, event): > pass > > if __name__ == '__main__': > app = model.Application(Minimal) > app.MainLoop() > > > > > def on_menuFileAbout_select(self, event): > > > > And, of course, if you replace the word "pass" with this, as > > instructed: > > > > result = dialog.alertDialog(self, 'It works!', 'Showing Off') > > > > it won't run, because the existing "pass" line isn't inside a def > > inside of a class. > > > > No, it didn't work because the author forgot to mention that you have > to do a: > > from PythonCard import model, dialog > > instead of just: > > from PythonCard import model > > I just tried it and it works. > > > > > B) Is the Notebook widget really supported? > > > > In the installed file "changelog.txt" (gets installed as part of > > PythonCard installation), it says: > > > > "added Notebook component, PageBackground, and testNotebook > > sample" > > > > But, the testNotebook sample is nowhere to be found. > > > > I haven't come across a need to use Notebook and so I can not say for > sure. Looking at notebook.py, it appears to be just a simple wrapper > on top of the wxWindow notebook. I would encourage you to post a > message to the mailing list and ask there. > > > > I looked lots of places, including the main SourceForge web site, > > and on the wiki, here: > > > > http://wiki.wxpython.org/index.cgi/PythonCard > > > > Both the main website and the wiki seem way out of date, and the > > latest dates I could find on both of them are sometime in 2004. > > > > Yes, sometime around 2004, the website updating stopped. Fortunately, > development didn't. There are quite a number of new things since then: > new resource editor (now call layout Editor, standalone exe creator, > and so forth). I even learn that a new sizer handler is in the work. > > Not saying that there are 10 programmers working 7/24 on it. It *is* > an Open Source project nevertheless. Nobody gets paid for doing it. > But there are development work going on. > > > > Finally, by following the mailing list archive link on the main > > website, I managed to find a reference to the notebook component on the > > ASPN site, where some guy named Brian wonders about the same thing as > > me, concerning the availability of the notebook component: > > > > http://aspn.activestate.com/ASPN/Mail/Message/pythoncard/2536825 > > > > and, that message led me here: > > > > http://article.gmane.org/gmane.comp.python.pythoncard/1060 > > > > where Kevin Altis admits that he forgot to include it in the 0.8.1 > > release! At least he provides a way to download it separately. But, > > gheesh, this is pretty poor for a new user. I was interested in using > > the notebook component right away, because I looked at the wxGlade > > tutorial before looking at PythonPage, and they use the notebook > > component in their example (and I decided I really want to use the > > component). > > > > To add insult to injury, after you download the zip file with the > > testNotebook stuff, the readme file says this: > > > > "Until we have a Notebook integrated into some of the other > > samples or tools this will serve as a basic test app, but I don't expect > > to include it in releases." > > > > > As with all Open Source projects, your mileage differs. PythonCard > does what *I* need to get done - and allowed me to get it done in a > *hurry*. May be you really need Notebook and may be it's true that > Notebook really doesn't work, I don't know. But if you managed to get > it working, write it up and get it included. That's what Open Source > Projects are all about. > > > > C) Are the websites being maintained? > > > It appears that the maintainer of the web site stopped updating it > since late 2004. I don't know why. May be he's been busy. May be he > got mad. I don't know. All I know is that I have been very > productive with what I need to get done (and earned a happy living with > the code I created) and I am very grateful to the people that worked on > it - past and present. > > I am not a "professional programmer" and so I probably can't contribute > to the development effort itself. However, I've gotten pretty good in > using most of the package (other then Notebook, I admit). So, if you > have any specific questions, please post it to the PythonCard list and > I'll try to help if I can. > > Cheers. From steve at holdenweb.com Thu Nov 2 21:36:08 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Nov 2006 02:36:08 +0000 Subject: is mod_python borked? In-Reply-To: <1162509979.221261.192440@m7g2000cwm.googlegroups.com> References: <1162480110.992783.267620@e3g2000cwe.googlegroups.com> <1162509979.221261.192440@m7g2000cwm.googlegroups.com> Message-ID: <454AAB18.1@holdenweb.com> grahamd at dscpl.com.au wrote: > walterbyrd wrote: > >>I am considering python, instead of php, for web-application >>development. I often see mod_python.criticisized as being borked, >>broken, or just plain sucking. >> >>Any truth to any of that? > > > I replied to you over on the mod_python mailing list when you reposted > the question there, but I'll copy to here my response for the benefit > of others. > > In answer to your question of whether mod_python is borked, the answer > is yes and no. > Nice summary. To be fair to Walter, it was me who reposted his question. But I think it's great that the whole of c.l.py is now up to speed on mod_python, so thanks! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From robert.kern at gmail.com Thu Nov 2 16:44:44 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 02 Nov 2006 13:44:44 -0800 Subject: Python in sci/tech applications In-Reply-To: <1162502997.175322.171730@e3g2000cwe.googlegroups.com> References: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> <1162489638.013433.102180@h48g2000cwc.googlegroups.com> <1162491753.605134.162700@i42g2000cwa.googlegroups.com> <1162502997.175322.171730@e3g2000cwe.googlegroups.com> Message-ID: John Coleman wrote: > Maybe I don't know what I'm looking for, but I downloaded Enthought a > few days ago and don't seem to find MinGW on my system. There are 2 > relatively small (totalling about 13 kb IIRC) *python* files deeply > buried in the distribution with mingw in their filename but nothing > like a gcc compiler. I've mostly used visual studio or code warrior for > C compiling, so again - maybe I don't know what I am looking for. It is in c:\Python24\Enthought\mingw32\, IIRC (I don't have it in front of me). Add c:\Python24\Enthought\mingw32\bin\ to your PATH environment variable, and gcc.exe should be executable. -- 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 walterbyrd at iname.com Sat Nov 18 11:44:54 2006 From: walterbyrd at iname.com (walterbyrd) Date: 18 Nov 2006 08:44:54 -0800 Subject: Python v PHP for web, and restarting Apache? In-Reply-To: <1163810800.915170.48580@e3g2000cwe.googlegroups.com> References: <1163783247.077263.8590@j44g2000cwa.googlegroups.com> <1163810800.915170.48580@e3g2000cwe.googlegroups.com> Message-ID: <1163868294.131526.308080@e3g2000cwe.googlegroups.com> sandra.eloff at gmail.com wrote: > > Python is much better suited to writing and mainting large web > applications though. > I have to ask: why is that? Because Python is more readable? Because Python runs faster? Is Python more stable for large scale applications? Does this apply when using Python with CGI, FastCGI, mod_python, or what? From rookswood at suburbian.com.au Sat Nov 4 22:03:44 2006 From: rookswood at suburbian.com.au (John Savage) Date: Sun, 05 Nov 2006 03:03:44 GMT Subject: To remove some lines from a file References: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> Message-ID: <061105000015310.05Nov06$rookswood@suburbian.com> Sebastian Busch writes: >The task is: > >"Remove the first two lines that don't begin with "@" from a file." > >How would you do it with sed? Why a sed solution in a python group? sed '/^@/!{G;/\n\n\n/{P;d;};s/[^\n]*//;h;d;}' data -- John Savage (my news address is not valid for email) From bugs at almad.net Sat Nov 4 09:40:36 2006 From: bugs at almad.net (Almad) Date: 4 Nov 2006 06:40:36 -0800 Subject: Python crushing on kinterbasdb connect @ FreeBSD Message-ID: <1162651236.607722.23800@i42g2000cwa.googlegroups.com> Hi, I uploaded my application on our production server running FreeBSD and I found it crashing at startup. Problem is in connecting to my Firebird database: kinterbasdb.connect(with either good or wrong arguments) is resolving in: python in free(): error: junk pointer, too high to make sense Abort trap (core dumped) I installed kinterbasdb manually while I need 3.2 version for DBClass and latest in ports is 3.1; could this be the problem? (rest of system is from ports) Thank You for any advice, Almad From gagsl-py at yahoo.com.ar Wed Nov 15 12:51:58 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 15 Nov 2006 14:51:58 -0300 Subject: modules and generated code In-Reply-To: <455B4F66.9000408@wiggly.org> References: <455B4F66.9000408@wiggly.org> Message-ID: <7.0.1.0.0.20061115145032.038b61e0@yahoo.com.ar> At Wednesday 15/11/2006 14:33, Nigel Rantor wrote: >I have an IDL file that is used to generate a set of stub and skeleton >code that is not human-modifiable. > >Eventually I would like to have my IDL in source control and have a >setup script able to generate my stubs and skels and install them for me. > >At the same time I want to produce code that uses this code but in the >same package. > >[...] >Basically, I want the same top-level package to have bits of code in >different directories, but because Python requires the __init__.py file >it only picks up the first one in PYTHONPATH. Put both directories in the same package. But this is the obvious thing, so maybe I'm missing something. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From john106henry at hotmail.com Sun Nov 19 20:22:34 2006 From: john106henry at hotmail.com (John Henry) Date: 19 Nov 2006 17:22:34 -0800 Subject: Looking for a graph (as in network, nodes) package Message-ID: <1163985754.768937.132890@h54g2000cwb.googlegroups.com> I am looking for a ready made simple graph package. I found an extensive one in the piana package but when I try to use just the graph portion, it fails to load because of the line: class Graph(object): ... It seems that their Graph is subclassed from "object" but I couldn't find a "object" class anywhere. So, I abandoned using that one. Before I reinvent the wheel and start writing one myself, can somebody point me to a ready made one? I am afraid Googling "Python Graph" wouldn't be much help (millions and trillions of hits). Thanks, From titogarcia_nospamplease_ at gmail.com Sun Nov 5 10:46:13 2006 From: titogarcia_nospamplease_ at gmail.com (=?ISO-8859-1?Q?Ernesto_Garc=EDa_Garc=EDa?=) Date: Sun, 05 Nov 2006 16:46:13 +0100 Subject: Is there a commas-in-between idiom? In-Reply-To: References: Message-ID: Tim Peters wrote: > More idiomatic as > > if len(list) > 0: > > and even more so as plain > > if list: > >> print list[0], >> for element in list[1:]: >> print ',', element, > > > Do you really want a space before and after each inter-element comma? No, but it was only an example. I usually go for string concatenation. > An often-overlooked alternative to playing with ",".join() is: > > print str(list)[1:-1] That's funny! Not that I like it more that the join solution, but funny nevertheless. Thank you, Ernesto From ptmcg at austin.rr._bogus_.com Sat Nov 18 06:29:01 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 18 Nov 2006 11:29:01 GMT Subject: basic python questions References: <1163829271.660193.70450@j44g2000cwa.googlegroups.com> Message-ID: <18C7h.72$_H5.25@tornado.texas.rr.com> wrote in message news:1163829271.660193.70450 at j44g2000cwa.googlegroups.com... >I have a simple assignment for school but am unsure where to go. The > assignment is to read in a text file, split out the words and say which > line each word appears in alphabetical order. I have the basic outline > of the program done which is: > And in general, this is one of the best "can anyone help me with my homework?" posts I've ever seen. A. You told us up front that it was your homework. B. You made an honest stab at the solution before posting, and posted the actual code. C. You ended with some specific questions on things that didn't work or that you wanted to improve. Your current program looks like at least A- material. Add use of sorted and enumerate, and handle that exception a little better, and you're getting into A+ territory. Out of curiosity, what school are you attending that is teaching Python, and under what course of study? -- Paul From steve at holdenweb.com Mon Nov 6 14:43:47 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Nov 2006 14:43:47 -0500 Subject: getchar [was: Re: Python-list Digest, Vol 38, Issue 72] In-Reply-To: References: Message-ID: <454F9073.8050803@holdenweb.com> Santosh Chikkerur wrote: > Hi Friends, > > How to use getchar( ) in python. I want to see the output of the program > ,step by step. > I have given print statements in between for the results.. > Hence i would like to print the output everytime there is > getchar().which is the > similar fn in python > [... several hundred lines of irrelevant digest omitted ...] In future please don't quote the whole of a digest just to ask a simple question! Instead send an email to python-list at python.org. Also, it helps if you can give a subject line that indicates what you are asking about. Python has getch() in Windows only, there is no getchar(). If you want your program to be portable to Linux/Unix as well then getch() won't do. I have seen a portable recipe, but my google-fu is low today so I'll have to let someone else point that out if you need it. However, if the Enter key will do then just try inserting raw_input("Hit Enter to continue: ") That'll work on any platform. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From larry.bates at websafe.com Mon Nov 20 12:54:54 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 20 Nov 2006 11:54:54 -0600 Subject: How to make a python file to a DLL or COM object? In-Reply-To: <1163989866.823548.87430@m73g2000cwd.googlegroups.com> References: <1163989866.823548.87430@m73g2000cwd.googlegroups.com> Message-ID: <4561EBEE.9060805@websafe.com> many_years_after wrote: > Hi: > > some one said we can make a python file to an COM object through > py2exe , but I haven't got the method. Could any one who knows tell me > how to do? > > Thanks > You may want to take a look here. See COM servers section. http://www.py2exe.org/old/ COM servers COM servers are built by passing a com_server keyword argument to the setup function, again the value must be a list of Python module names containing one or more COM server classes (identified by their _reg_progid_ attribute): # setup.py from distutils.core import setup import py2exe setup(com_server=["win32com.server.interp"]) -Larry From rowen at cesmail.net Fri Nov 3 14:52:52 2006 From: rowen at cesmail.net (Russell E. Owen) Date: Fri, 03 Nov 2006 11:52:52 -0800 Subject: setting up wxPython on a Mac References: <454B6DB4.4040107@kevin-walzer.com> <454B8837.9060103@kevin-walzer.com> Message-ID: In article <454B8837.9060103 at kevin-walzer.com>, Kevin Walzer wrote: >Brian Blais wrote: >I'm not sure about numpy/scipy/matplotlib. I don't think there are >pre-built packages for them; you may have to build them from source. You >could also post to the MacPython mailing list, someone there has >probably looked at this already. There are prebuilt extension for these for Python 2.4.x available from . Packages for 2.5 will show up eventually, but meanwhile if you want prebuilt then use python 2.4.4. For python itself, I recommend using the Mac installer available from the standard python web site (rather than the package available from ). -- Russell From fredrik at pythonware.com Sat Nov 11 11:16:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Nov 2006 17:16:33 +0100 Subject: newbie: minidom In-Reply-To: <4555F394.80802@redlinepy.com> References: <4555F394.80802@redlinepy.com> Message-ID: Paul Watson wrote: >> why? the documents are equivalent, and any XML application that >> requires an explicit UTF-8 encoding declaration is broken. > > Explicit is better than implicit. inventing your own XML standard is no way better than using the existing one. From fredrik at pythonware.com Thu Nov 30 02:01:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 30 Nov 2006 08:01:48 +0100 Subject: Python Question About Compiling. In-Reply-To: <5b0fce7a0611292102g4a345b49h2a6e9c1f51ab4003@mail.gmail.com> References: <5b0fce7a0611292057p4d429226v9d3416ac9712e2@mail.gmail.com> <5b0fce7a0611292102g4a345b49h2a6e9c1f51ab4003@mail.gmail.com> Message-ID: Scheol Service wrote: > Im just unsure on how to compile python code into .exe executionable > files. Is there a simple way to do this? typing "compile python code" into google gives you http://effbot.org/zone/python-compile.htm which gives you some background, and links to a bunch of bundling tools. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Nov 27 13:11:56 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 27 Nov 2006 19:11:56 +0100 Subject: Calling a thread asynchronously with a callback References: Message-ID: <4t0o3cF11o4u1U1@mid.individual.net> Edwin Gomez wrote: > I'm a C# developer and I'm new to Python. I would like to know if > the concept of Asynchronous call-backs exists in Python. Sure. Either with this: http://twistedmatrix.com/projects/core/documentation/howto/async.html Or manually using select(). > Basically what I mean is that I dispatch a thread and when the > thread completes it invokes a method from the calling thread. > Sort event driven concept with threads. What you describe here isn't the only way to do asynchronous callbacks. See above for a simpler way. Regards, Bj?rn -- BOFH excuse #233: TCP/IP UDP alarm threshold is set too low. From george.sakkis at gmail.com Tue Nov 21 14:04:23 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 21 Nov 2006 11:04:23 -0800 Subject: Why is class decorator on method loosing self? References: Message-ID: <1164135863.270437.80340@b28g2000cwb.googlegroups.com> c james wrote: > I want to use the LRU decorator posted at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498110 > on a class method. However, it complains about missing arguments. The > missing argument is `self`. I could use @classmethod but what I really > need is an instance method. I don't see how and was hoping someone else > might know the way. > > Here is an example with taking that recipe as lru.py > > import lru > > class Foo(object): > def banner(self): > print "Testing method" > > @memoize(3) > def min_max(self, sequence): > self.banner() > return min(sequence), max(sequence) > > foo = Foo() > print foo.min_max([9,7,5,3,1]) > > > Traceback (most recent call last): > ... > File "lru.py", line 48, in __call__ > value = self.func(*args, **kwargs) > TypeError: min_max() takes exactly 2 arguments (1 given) I don't think you can make it work without resorting to metaclass magic. At the point of decoration min_max is still a function, not a method, because class Foo has not been created yet. Here's a way to do it with a custom metaclass; whether you really want to do it is a different matter: First off, remove the decoratorargs class and have memoize inherit from object: class memoize(object): # class body stays the same Then add the following: # this is general enough to be moved to a separate module class CustomizeMeta(type): def __init__(cls, name, bases,dict): for attr,val in dict.iteritems(): if hasattr(val, '__customize'): setattr(cls, attr, getattr(val,'__customize')(cls)) def memoizefunction(*args, **kwds): return lambda func: memoize(func, *args, **kwds) def memoizemethod(*args, **kwds): from types import MethodType def wrapper(func): func.__customize = lambda cls: \ MethodType(memoize(func,*args,**kwds), None, cls) return func return wrapper #==== examples ============================================= @memoizefunction(3) def fib(n): return (n > 1) and (fib(n - 1) + fib(n - 2)) or 1 class Foo(object): __metaclass__ = CustomizeMeta def __init__(self, i): self._i = i def banner(self): print "Testing method" @memoizemethod(3) def min_max(self, sequence): self.banner() return min(sequence), max(sequence) foo = Foo() print foo.min_max([9,7,5,3,1]) George From metaperl at gmail.com Mon Nov 27 15:03:00 2006 From: metaperl at gmail.com (metaperl) Date: 27 Nov 2006 12:03:00 -0800 Subject: Generating header information using ElementTree In-Reply-To: <1164587885.050983.282680@l39g2000cwd.googlegroups.com> References: <1164574832.936947.69420@h54g2000cwb.googlegroups.com> <1164579522.671325.36260@14g2000cws.googlegroups.com> <4suidqF10rlh1U1@mid.uni-berlin.de> <1164583078.233238.227010@45g2000cws.googlegroups.com> <1164586070.655741.256800@h54g2000cwb.googlegroups.com> <1164587885.050983.282680@l39g2000cwd.googlegroups.com> Message-ID: <1164657780.012257.146870@h54g2000cwb.googlegroups.com> And dont forget that you can use triple quotes to get rid of all the quote-escaping you are using: $ python >>> """ ... ... ho ... ... """ '\n\nho\n\n' >>> Craig wrote: > John Machin wrote: > > > Craig wrote: > > > > > Great. Got that sorted. The problem I have now is that some of the > > > XML data is not copied across to the file when I have the text > > > information included. The number of characters that is lost is equal > > > to the number of characters that is in the block of text I entered > > > before. The code I am using is: > > > > > > def WriteXMLRecord ( record, XMLFileBaseName, root): > > > RecordName = SubElement(root, "Log") > > > #iterate through all the fields in the record > > > for key in record: > > > # write the key and its data > > > test = SubElement(RecordName, key) > > > test.text = str(record[key]) > > > tree = ElementTree(root) > > > tree.write(XMLFileBaseName) > > > > I'm guessing, based on reading the docs for the write method, that you > > should be using the file handle, rather than the file name, if the file > > is already opened. So (1) change the name of the 2nd arg to > > XMLFileHandle or somesuch, and in the caller, use outFile (the handle) > > instead of "record.xml". > > > > > > > > def main(): > > > outFile = open("record.xml", 'w') > > > outFile.write(""" > > > > > > \n\n""") > > > > > > root = Element("Log") > > > WriteXMLRecord(data1, "record.xml", root) > > > WriteXMLRecord(data2, "record.xml", root) > > > WriteXMLRecord(data3, "record.xml", root) > > > outFile.close() > > > > > HTH, > > John > > Great. Got it. Thanks so much for all your help. > > > Craig From f.braennstroem at gmx.de Sat Nov 4 09:29:00 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sat, 4 Nov 2006 15:29:00 +0100 Subject: small python cgi webserver References: <1162635479.491109.15640@h54g2000cwb.googlegroups.com> Message-ID: Hi Norbert, * Norbert Kaufmann wrote: > Fabian Braennstroem wrote: > [...] >> >> Maybe, I understood something wrong, but I thought that the >> above 'webserver' script would replace apache in my case; at >> least I hoped!? >> > > It does. The 'ServerRoot' and 'DocumentRoot' directories are the > directories you are starting your webserver in. > Create a 'cgi' directory inside this and consider that you have to name > it in the serverscript in relation to the serverroot! > > > cgi_directories=["/home/fab/Desktop/cgi-bin"] > > > This means you have to start your server inside directory '/'. I tried this, but it does not help ... a wait, the leading '/' is the problem. Thanks! > > If you start your server in your home dir '/home/fab' then you have to > name your cgi_directories ['/Desktop/cgi-bin']. > > In your response (cgi-script) you have to divide the header from the > content '\r\n\r\n'. I am not sure, what that means!? ... but it works :-) Greetings! Fabian From inq1ltd at verizon.net Sat Nov 4 19:52:07 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Sat, 04 Nov 2006 19:52:07 -0500 Subject: disabledforeground or similar for Entry (in Tkinter) In-Reply-To: <1162656214.176092.46530@f16g2000cwb.googlegroups.com> References: <1162656214.176092.46530@f16g2000cwb.googlegroups.com> Message-ID: <200611041952.07546.inq1ltd@verizon.net> On Saturday 04 November 2006 11:03, Dustan wrote: > Back in this post, I attempted to make a label > look like a button: > http://groups.google.com/group/comp.lang.python >/browse_thread/thread/a83195d3970a6851/2053cbaec >1bc1f19?auth=DQAAAHkAAAAMDAWnhNnzpuKlwOKZUwAGUTt >T2Ay-EAB7rCY6SnwfnDzZ98M37bZDW2Is0LrBVrr8XEgPfcu >OkiUE-CrSsKbBSX-67voDUXfbATBd0eYNMClezby4EXT2fuL >m6f0llJ_xMO8BfkjVho_7CZvlf_9tNGnJixTbq8zr21ODZBh >ouQ > > Alright, I've learned my lesson - don't use a > new widget; modify the old one. > > Except the Entry widget doesn't have a > disabledforeground option. Neither does the > Text widget, but IDLE seems to accomplish > making a disabled Text look the same as an > enabled Text in the IDLE Help section. > > No, foreground (fg) and background (bg) don't > make a difference; it still changes the color > of the Entry widget upon disabling. > > There must be something I'm missing here... My previous post was hasty and we all know, "Haste makes waste." Try this; If you use wiget-01.pack_forget() or wiget-01.grid_forget(), you can now build wiget-02 using wiget-02.pack or grid() for the same location. You can reinstall uninstalled wigets by using pack() or grid() again for those hidden wigets. However only after uninstalling for the wigets in those locations. root = Tk() test1 = Button(root, text='Test No.1 button', bg = 'yellow', width = 15, height = 10) test1.grid(row=0, column=0) test1.grid_forget() test2 = Button(root, text='Test #2 button', bg = 'green', width = 15, height = 10) test2.grid(row=0, column=0) mainloop() jim-on-linux http://www.inqvista.com From ronrsr at gmail.com Fri Nov 10 12:30:27 2006 From: ronrsr at gmail.com (ronrsr) Date: 10 Nov 2006 09:30:27 -0800 Subject: SyntaxError: Invalid Syntax. In-Reply-To: <1163179622.691812.96170@h48g2000cwc.googlegroups.com> References: <1163178099.156160.29280@k70g2000cwa.googlegroups.com> <1163178336.281812.140580@f16g2000cwb.googlegroups.com> <1163178581.231837.18120@h48g2000cwc.googlegroups.com> <1163179622.691812.96170@h48g2000cwc.googlegroups.com> Message-ID: <1163179827.707089.48920@m73g2000cwd.googlegroups.com> the syntax error comes in the main program, in any line that follows the import statement. ronrsr wrote: > the exact code that is triggering the error message is: > > zc = zsql.connect() > > > exact error message: SyntaxError: Invalid Syntax > > > but any statement that follows the import statement will trigger it. > > bests, > > r-sr- > > > > > Roberto Bonvallet wrote: > > ronrsr wrote: > > > thanks for the speedy answer. what i meant was: > > > > > > Could you please copy and paste the exact code that is triggering the > > error, and the exact error message? > > > > (BTW, in Python you don't need to end your statements with a semi-colon) > > -- > > Roberto Bonvallet From cemerick at snowtide.com Sat Nov 18 10:34:15 2006 From: cemerick at snowtide.com (Chas Emerick) Date: Sat, 18 Nov 2006 10:34:15 -0500 Subject: lxml/ElementTree and .tail In-Reply-To: References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> <761846B7-E374-41FE-8804-CBB3D42FD4D2@snowtide.com> <1163835505.102190.140060@b28g2000cwb.googlegroups.com> Message-ID: <894503B9-B571-42E3-9FA0-B0C67D333A3D@snowtide.com> On Nov 18, 2006, at 5:09 AM, Fredrik Lundh wrote: > Uche Ogbuji wrote: > >> I certainly have never liked the aspects of the ElementTree API under >> present discussion. But that's not as important as the fact that I >> think the above statement is misleading. There has always been a >> battle in XML between the people who think the serialization is >> preeminent, and those who believe some data model is preeminent, but >> the reality is that XML 1.0 (an 1.1) is a spec *defined* by its >> serialization. > > sure, the computing world is and has always been full of people who > want > the simplest thing to look a lot harder than it actually is. after > all, > *they* spent lots of time reading all the specifications, they've > bought > all the books, and went to all the seminars, so it's simply not fair > when others are cheating. [snip] > and keep patting our- > selves on the back, while the rest of the world is busy routing around > us, switching to well-understood XML subsets or other serialization > formats, simpler and more flexible data models, simpler API:s, and > more robust code. and Python ;-) That's flatly unrealistic. If you'll remember, I'm not one of "those people" that are specification-driven -- I hadn't even *heard* of Infoset until earlier this week! However, I am driven to ensure that the code I (and we) write works *as others expect* when confronted by any of the billions of XML documents out there. Simpler is better, and better is better (thus why I am in python-land), unless that simplicity makes it difficult to play nicely with others. Shrugging off the way everyone else does things reminds me of various CSS fanatics I know of that simply won't use tables or IE CSS compatibility hacks, even if that's what's needed to get things to work. I've never been involved in any "XML battles", but to Uche's point, I would speculate (only on the basis of personal interactions and anecdotes) that some overwhelming majority of the developers out there care for nothing but the serialization, simply because that's how one plays nicely with others. I would count myself in that group as well, although I do recognize that there is a worthy academic exercise in exploring the data-model-centric XML worldview. OT: Uche, 4suite XML is tops! Thank you very much for that. - Chas From farraige at go2.pl Wed Nov 8 05:18:14 2006 From: farraige at go2.pl (Farraige) Date: 8 Nov 2006 02:18:14 -0800 Subject: please help with optimisation of this code - update of given table according to another table Message-ID: <1162981094.820174.65440@b28g2000cwb.googlegroups.com> Hi I need your help... I am implementing the method that updates given table (table is represented as list of lists of strings) according to other table (some kind of merging)... This method takes following arguments: t1 - table we would like to update t2 - table we would like to take data from keyColumns - list of key indexes e.g. [0,1] columnsToBeUpdated - list of column indexes we would like to update in our table T1 e.g [2,4] Let's say we have a table T1: A B C D E --------------- 1 4 5 7 7 3 4 0 0 0 and we call a method mergeTable(T1, T2, [0,1], [2,4]) It means that we would like to update columns C and E of table T1 with data from table T2 but only in case the key columns A and B are equal in both tables.... I grant that the given key is unique in both tables so if I find a row with the same key in table T2 I do merging, stop and go to next row in table T1... Let's say T2 looks following: A B C D E --------------- 2 2 8 8 8 1 4 9 9 9 So after execution of our mergeTable method, the table T1 should look like : A B C D E 1 4 9 7 9 3 4 0 0 0 The 2nd row ['3', '4', '0' ,'0', '0'] didn't change because there was no row in table T2 with key = 3 ,4 The main part of my algorithm now looks something like ... merge(t1, t2, keyColumns, columnsToBeUpdated) ....... for row_t1 in t1: for row_t2 in t2: if [row_t1[i] for i in keyColumns] == [row_t2[j] for j in keyColumns]: # the keys are the same for colName in columnsToBeUpdated: row_t1[colName] = row_t2[colName] # go outside the inner loop - we found a row with # the same key in the table break In my algorithm I have 2 for loops and I have no idea how to optimise it (maybe with map? ) I call this method for very large data and the performance is a critical issue for me :( I will be grateful for any ideas Thanks in advance! From fredrik at pythonware.com Mon Nov 13 10:41:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Nov 2006 16:41:23 +0100 Subject: httplib.InvalidURL: nonnumeric port: For charactersintheproxypassword in URL References: <1163408210.915911.327430@k70g2000cwa.googlegroups.com><1163424914.967174.302610@e3g2000cwe.googlegroups.com> <1163431557.397172.175850@f16g2000cwb.googlegroups.com> Message-ID: "Phoe6" wrote: > proxy_password = urllib.quote(proxy_password_orig) make that: proxy_password = urllib.quote(proxy_password_orig, "") From DustanGroups at gmail.com Sun Nov 12 11:10:35 2006 From: DustanGroups at gmail.com (Dustan) Date: 12 Nov 2006 08:10:35 -0800 Subject: reduce to be removed? In-Reply-To: References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163288885.884417.218270@f16g2000cwb.googlegroups.com> <1163290526.013063.245130@m7g2000cwm.googlegroups.com> <1163295752.701124.322620@h54g2000cwb.googlegroups.com> <1163298336.778941.138540@m73g2000cwd.googlegroups.com> Message-ID: <1163347835.815187.216180@e3g2000cwe.googlegroups.com> Alright, I can see I'm a bit outvoted here. I tried your suggestions and it worked fine. I'll also try to consider in the future that part of the problem might be lack of information conveyed on my part. From hakonrk at fys.uio.no Sat Nov 11 15:37:35 2006 From: hakonrk at fys.uio.no (Haakon Riiser) Date: Sat, 11 Nov 2006 20:37:35 +0000 (UTC) Subject: httplib continuation packets Message-ID: After a long debugging session while scripting my webmail, I believe I have traced the problem to the way httplib sends POST requests. I have compared tcpdump listings from Python 2.4.3 and 2.5.0's httplib (via urllib/urllib2), Perl's LWP::UserAgent 2.033 and Firefox 2.0. Only Python sends the request in such a way that the mailserver closes the connection before I get any data from the POST request (immediate FIN packet after the POST request). httplib always sends the urlencoded POST data in a separate packet from the HTTP headers, and this seems to cause problems with the web interface in Ipswitch-IMail/8.05 (the software running on Doteasy's webmail). Firefox 2.0 has most of the headers in a single packet, but unlike httplib, it always places a couple of headers in the continuation packet as well (usually the content-length and content-type headers). LWP::UserAgent 2.033 doesn't use continuation at all, and sends everything in a single packet. Is this a bug in httplib or the web server? Is there a workaround, or should I use Perl for this? -- Haakon From gagsl-py at yahoo.com.ar Thu Nov 9 15:36:38 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 09 Nov 2006 17:36:38 -0300 Subject: cross connecting In-Reply-To: References: Message-ID: <7.0.1.0.0.20061109173013.03fd1890@yahoo.com.ar> At Thursday 9/11/2006 17:17, km wrote: >I have a c executable in machine A which cannot execute on B. >I am on machine B and i need python program to connect to A via >telnet and run the program with arguments passed from program on >B and at the end fetch back results to machine B. >i would like to know , which set of modules are suitable for this >sort of a work ? Using rsh (linux) or psexec (windows; www.sysinternals.com) you can execute *any* program remotely (of course certain security constraints apply). From the python point of view, you're executing a command and capturing its output; use the subprocess module. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From andymac at bullseye.apana.org.au Thu Nov 9 16:57:48 2006 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 10 Nov 2006 07:57:48 +1000 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <45533D9F.5020002@chamonix.reportlab.co.uk> References: <1163072637.924217.90610@h54g2000cwb.googlegroups.com> <45533D9F.5020002@chamonix.reportlab.co.uk> Message-ID: <4553A45B.6080603@bullseye.andymac.org> Robin Becker wrote: > I think it uses sysv semaphores and although freeBSD 6 has them perhaps there's > something I need to do to allow them to work. IIRC, you need to explicitly configure loading the kernel module, or compile the kernel with the necessary option in the config file. -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From paddy3118 at netscape.net Thu Nov 23 00:13:08 2006 From: paddy3118 at netscape.net (Paddy) Date: 22 Nov 2006 21:13:08 -0800 Subject: Abelson and Python In-Reply-To: <1164239517.067445.179320@e3g2000cwe.googlegroups.com> References: <1164239517.067445.179320@e3g2000cwe.googlegroups.com> Message-ID: <1164258788.650158.118150@h54g2000cwb.googlegroups.com> bearophileHUGS at lycos.com wrote: > While studying the SICP video lectures I have to twist my mind some to > completely understand the lessons. I implement the programs shown there > in both Python and Scheme, and I find the Python implementations > simpler to write (but it's not a fair comparison because I know very > little Scheme still). > > Now some things are changing: > http://lambda-the-ultimate.org/node/1840 > > >The MIT is going to change its curriculum structure that was famous for teaching Scheme in introductory courses. One force behind the reform is no one else than Harold Abelson, famous for his marvelous Scheme opus SICP.< > >The first four weeks of C1 will be a lot like the first four weeks of 6.001, Abelson said. The difference is that programming will be done in Python and not Scheme.< > > > Someone is translating the SIPC programs in Python too: > http://www.codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages#Python > > With slides and code from lectures: > http://courses.csail.mit.edu/6.01/ > http://courses.csail.mit.edu/6.01/fall06/calendar.html > > I like Scheme a bit too, but I consider this is a small victory for > Python :-) > > Bye, > bearophile Hi Bearophile. (Is your name pronounced Beer-owe-file, or Bear-oh-fi-lee, just wondered :-) ? I too have heard about the MIT course changing to Python elsewhere and wanted to know why it was talked about so much? I'm from England, I know that MIT is a very prestigious university, but if Cambridge changed a course, or better still, The Open University changed a similar course to Python, I think I'd be hard pressed to hear about it. Is the MIT course syndicated to Universities around America or something? Cheers, Paddy. From stefan.behnel-n05pAM at web.de Thu Nov 16 08:35:12 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 16 Nov 2006 14:35:12 +0100 Subject: lxml/ElementTree and .tail In-Reply-To: References: <455C1887.6060602@web.de> Message-ID: <455C6910.9010209@web.de> Fredrik Lundh wrote: > Stefan Behnel wrote: > >> If you want to copy part of of removed element back into the tree, >> feel free to do so. > > and that can of course be done with a short helper function. Oh, and obviously with a custom Element class in lxml that does this automatically for you behind the scenes. http://codespeak.net/lxml/element_classes.html http://codespeak.net/lxml/element_classes.html#default-class-lookup Stefan From utabintarbo at gmail.com Wed Nov 8 07:47:09 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 8 Nov 2006 04:47:09 -0800 Subject: Searching for a module to generate GUI events In-Reply-To: References: Message-ID: <1162990029.409193.246830@b28g2000cwb.googlegroups.com> Stephan Kuhagen wrote: > Hello > > I'm searching for a Python Module which is able to generate GUI events on > different platforms (at least X11 and Windows, MacOSX would be nice), but > without being a GUI toolkit itself. So PyTk is not a choice, because I need > to use it, to control GUIs of other Programs. I want to generate Mouse > events (move, click etc.) and keyboard events and inject them directly into > the event-queue of the underlying window system. > > Does somebody know such a module or do I have to utilize platform specific > tools from within Python? > > Regards and Thanks > Stephan http://pywinauto.pbwiki.com/ for Win32 From fredrik at pythonware.com Thu Nov 23 04:56:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Nov 2006 10:56:32 +0100 Subject: Finding the carret position in a regular expression In-Reply-To: <1164274616.881372.276400@l39g2000cwd.googlegroups.com> References: <1164274616.881372.276400@l39g2000cwd.googlegroups.com> Message-ID: Tool69 wrote: > supposed I've got the following text : > > mytext = "for in :" > > with the following simple pattern : pattern = "<[a-z]+>" > > I use re.findall(pattern, mytext) wich returns : > ['',''] > > Now, I want my prog to return the positions of the returned list > elements, ie : > was found at position 5 in mytext > was found at position 16 in mytext "findall" doesn't return that information; use "finditer" instead, and use the "span" or "start" method on the returned match object to get the position: for m in re.finditer(pattern, mytext): print m.span() From dimitri.pater at gmail.com Sat Nov 18 18:25:44 2006 From: dimitri.pater at gmail.com (dimitri pater) Date: Sun, 19 Nov 2006 00:25:44 +0100 Subject: What do I look for in a shared Python host? In-Reply-To: <1163877328.071239.191260@f16g2000cwb.googlegroups.com> References: <1163815003.733525.6380@b28g2000cwb.googlegroups.com> <1163877328.071239.191260@f16g2000cwb.googlegroups.com> Message-ID: Hi, is there any reason for you wanting to use a shared host? Just asking.. Maybe you could use a VPS as this is not too expensive these days. Of course, it would require more work to set things up. But it's not too hard... (eg using apt-get,webmin,some basic Linux skills using the command line) regards, Dimitri (I use a VPS at rimuhostig ($20/month), but there are many, many more) On 18 Nov 2006 11:15:28 -0800, Fuzzyman wrote: > > > walterbyrd wrote: > > For example: > > > > - If I want to use Django, I need either FastCGI or Apache > > 2.X/mod_python 3.x > > > > - if I want to use TurboGears, I need Python 2.4: not 2.3 and not 2.5 > > > > - I have just learned that some hosters have T&Cs that forbid long > > running processes. I am not sure exactly what that means. Except I > > understand it can be a problem if using Cherrypy/TurboGears > > > > - I have read that mod_python before 3.x can be difficult > > > > What other "gotchas" would I look for? > > The best host for Python (including Django and Turbogears), try > webfaction. They used to be known as Python-hosting.com and offer great > support for Python. > > Fuzzyman > http://www.voidspace.org.uk/index2.shtml > > -- > http://mail.python.org/mailman/listinfo/python-list > -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From i80and at gmail.com Thu Nov 9 22:50:57 2006 From: i80and at gmail.com (i80and) Date: 9 Nov 2006 19:50:57 -0800 Subject: Having problems with urlparser concatenation In-Reply-To: References: <1163114626.595813.286260@b28g2000cwb.googlegroups.com> Message-ID: <1163130657.069453.278140@m7g2000cwm.googlegroups.com> Thank you! Fixed my problem perfectly! Gabriel Genellina wrote: > At Thursday 9/11/2006 20:23, i80and wrote: > > >I'm working on a basic web spider, and I'm having problems with the > >urlparser. > >[...] > > SpliceStart = Website.find('', SpliceStart)) > > > > ParsedURL = > >urlparse((Website[SpliceStart+9:(SpliceEnd+1)])) > > robotparser.set_url(ParsedURL.hostname + '/' + > >'robots.txt') > >----- > >Traceback (most recent call last): > > File "C:/Documents and Settings/Andrew/Desktop/ScoutCode-0.09.py", > >line 120, in > > FindLinks(Website) > > File "C:/Documents and Settings/Andrew/Desktop/ScoutCode-0.09.py", > >line 84, in FindLinks > > robotparser.read() > > File "C:\Program Files\Python25\lib\robotparser.py", line 61, in read > > f = opener.open(self.url) > > File "C:\Program Files\Python25\lib\urllib.py", line 190, in open > > return getattr(self, name)(url) > > File "C:\Program Files\Python25\lib\urllib.py", line 451, in > >open_file > > return self.open_local_file(url) > > File "C:\Program Files\Python25\lib\urllib.py", line 465, in > >open_local_file > > raise IOError(e.errno, e.strerror, e.filename) > >IOError: [Errno 2] The system cannot find the path specified: > >'en.wikipedia.org\\robots.txt' > > > >Note the last line 'en.wikipedia.org\\robots.txt'. I want > >'en.wikipedia.org/robots.txt'! What am I doing wrong? > > No, you don't want 'en.wikipedia.org/robots.txt'; you want > 'http://en.wikipedia.org/robots.txt' > urllib treats the former as a file: request, here the \\ in the > normalized path. > You are parsing the link and then building a new URI using ONLY the > hostname part; that's wrong. Use urljoin(ParsedURL, '/robots.txt') instead. > > You may try Beautiful Soup for a better HTML parsing. > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! > ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From kw at kevin-walzer.com Fri Nov 3 13:19:35 2006 From: kw at kevin-walzer.com (Kevin Walzer) Date: Fri, 03 Nov 2006 13:19:35 -0500 Subject: setting up wxPython on a Mac In-Reply-To: References: <454B6DB4.4040107@kevin-walzer.com> Message-ID: <454B8837.9060103@kevin-walzer.com> Brian Blais wrote: > Kevin Walzer wrote: >> Brian Blais wrote: >>> Hello, >>> >>> I have a wxPython program that I would like to give to a friend of mine >>> who has a Mac. Is there a resource out there that can tell me what >>> steps I need to follow to do this? >> Install Python from the Python website--a Python 2.5 installer is >> available for the Mac. >> >> Install wxPython from the wxPython website--an installer for the latest >> version of wxPython for the Mac is also available. >> >> That should do it. >> > > sounds easy. If I need the numpy/scipy/matplotlib combo, is it that > straightforward? On windows it is, on Linux is definitely is not. > > thanks, > > bb > > I'm not sure about numpy/scipy/matplotlib. I don't think there are pre-built packages for them; you may have to build them from source. You could also post to the MacPython mailing list, someone there has probably looked at this already. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bignose+hates-spam at benfinney.id.au Tue Nov 21 20:31:14 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 22 Nov 2006 12:31:14 +1100 Subject: Is time.time() < time.time() always true? References: <1164150625.377064.112550@j44g2000cwa.googlegroups.com> <7.0.1.0.0.20061121213222.041021c8@yahoo.com.ar> Message-ID: <873b8cw9lp.fsf@benfinney.id.au> Gabriel Genellina writes: > The only thing Python can guarantee, is that the left expression is > evaluated before the right one (5.13 Evaluation order, Language > Reference). Thanks, that answers my question asked elsewhere. -- \ "One thing vampire children have to be taught early on is, | `\ don't run with a wooden stake." -- Jack Handey | _o__) | Ben Finney From nick at craig-wood.com Wed Nov 29 07:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 29 Nov 2006 06:30:03 -0600 Subject: Wrapping A Shell References: Message-ID: Jeremy Moles wrote: > I'm not sure if this is really the right place to ask this question, but > since the implementation is in Python, I figured I'd give it a shot. > > I want to "wrap" a shell process using popen inside of python program > rather than creating a new shell process for each line I process in the > app. For example, the code might look like: > > > std = stdin, stdout, stderr = os.popen3("bash") > > print >> stdin, "ls" > > print stdout.readline() > > However, it appears my understanding of popen (or perhaps buffered IO) > is off somewhere, because this certainly doesn't work anything like I > expect it to (it hangs on stdout.readline). > > Obviously the example above is very contrived, but eventually I'll be > using this in an OpenGL "terminal" widget. Am I approaching this the > wrong way? Short answer: use pexpect http://pexpect.sourceforge.net/ Long answer: Firstly modern pythonistas use subprocess instead of os.popen*. Secondly, buffering is going to cause you trouble and possible deadlocks. There are two ways to rid yourself of deadlock. 1) read and write from seperate threads / processes. This is the traditional unix way 2) use non blocking IO Here is a possible way to solve the problems with subprocess (unix only) and non blocking IO. However I suspect you really want to use pexpect for this job... from os import O_NONBLOCK from errno import EAGAIN from subprocess import Popen, PIPE from fcntl import fcntl, F_SETFL, F_GETFL from time import time p = Popen(["/bin/bash", "-i"], shell=False, bufsize=0, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) # Make output streams non blocking (unix only) for fd in (p.stdout.fileno(), p.stderr.fileno()): fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK) def read_output(p, timeout=1.0): """Read the output from the subprocess, with timeout""" end_time = time() + timeout output = "" while time() < end_time: try: output += p.stdout.read(1024) except IOError, e: if e.errno != EAGAIN: raise return output p.stdin.write("ls\n") print read_output(p) p.stdin.write("uname -a\n") print read_output(p) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From robin at alldunn.com Wed Nov 8 10:47:38 2006 From: robin at alldunn.com (Robin Dunn) Date: Wed, 08 Nov 2006 07:47:38 -0800 Subject: ANN: wxPython 2.7.2.0 In-Reply-To: <20061108151134.73765.qmail@web51113.mail.yahoo.com> References: <20061108151134.73765.qmail@web51113.mail.yahoo.com> Message-ID: <4551FC1A.9090606@alldunn.com> Kenneth Long wrote: > Is there a new version of Demo Docs released also? > > I get this error from Sourceforge after clicking on > the link at wxPython page. > > Could not read file. > > Go back. > /home/ftp/pub/sourceforge//w/wx/wxpython/wxPython2.7-win32-docs-demos-2.7.2.0.exe Looks like there was an error when building that installer file. I'll get it fixed and upload it again soon. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From deets at nospam.web.de Thu Nov 16 04:07:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 16 Nov 2006 10:07:56 +0100 Subject: How to make a python file to a DLL? In-Reply-To: <1163663993.261179.146630@m7g2000cwm.googlegroups.com> References: <1163663993.261179.146630@m7g2000cwm.googlegroups.com> Message-ID: <4s2o3aFtt1umU1@mid.uni-berlin.de> many_years_after schrieb: > Any solution? http://wiki.python.org/moin/elmer From bytter at gmail.com Wed Nov 29 12:51:04 2006 From: bytter at gmail.com (Bytter) Date: 29 Nov 2006 09:51:04 -0800 Subject: libboost, python, and dijkstra shortest path Message-ID: <1164822664.826189.28760@80g2000cwy.googlegroups.com> Hi everyone, I need to implement a very quick (performance-wise) Dijkstra shortest path in python, and found that libboost already has such thing. Problem is: I cannot find the installation package for my Python 2.4 under windows. Can someone please provide me instructions for installing libboost for python? In alternative, if someone can point out to a fast Dijkstra shortest path in python (the network is over 1 million vertexes), I would appreciate. Thanks in advance, Hugo Ferreira From bdesth.quelquechose at free.quelquepart.fr Wed Nov 8 17:54:04 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 08 Nov 2006 23:54:04 +0100 Subject: is this the right way to do subclasses? In-Reply-To: <45524f40$0$32365$c3e8da3@news.astraweb.com> References: <45522074$0$17101$c3e8da3@news.astraweb.com> <45524f40$0$32365$c3e8da3@news.astraweb.com> Message-ID: <45525b3e$0$32029$426a34cc@news.free.fr> John Salerno a ?crit : > Peter Otten wrote: > >> You may need a no-op implementation of fix_attributes() in the Character >> class. > > > What does that mean? Is that in case I use Character directly to create > an object? Most propbably it can be useful for other character classes that don't need too fix attributes. > Would that just be a 'pass' statement? Yes. From podi.ex at gmail.com Thu Nov 9 21:56:51 2006 From: podi.ex at gmail.com (Podi) Date: 9 Nov 2006 18:56:51 -0800 Subject: urllib en https In-Reply-To: <87r6yby5d8.fsf@pobox.com> References: <4508649d$0$4521$e4fe514c@news.xs4all.nl> <4508720c$0$4520$e4fe514c@news.xs4all.nl> <2C6Og.1077$UG4.342@newsread2.news.pas.earthlink.net> <87r6yby5d8.fsf@pobox.com> Message-ID: <1163127410.938230.180740@h54g2000cwb.googlegroups.com> > > As I recall, ActiveState doesn't distribute the SSL package that the > > python.org package contains. But... It is possible to copy the SSL > > related files from a python.org package into the ActiveState > > installation. > Are there any instructions on doing this? My Python installation from cygwin seems to have SSL but not the ActiveState. However, I really like the ActiveState PythonWin UI. I would be much appreciated if anyone can provide pointer to get the SSL in AS Python to work. Thanks in advance. P From Roberto.Bonvallet at cern.ch Thu Nov 30 08:21:55 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Thu, 30 Nov 2006 13:21:55 +0000 (UTC) Subject: PythonTidy References: Message-ID: Chuck Rhode wrote: > I couldn't find a routine to clean up, regularize, and reformat Python > code, so I wrote one: > > http://www.lacusveris.com/PythonTidy/PythonTidy.python > > Now, I'm looking for beta-testers. Compensation is a bit on the low > side. In fact it's limited to the satisfaction of helping out. $ cat test.py #!/usr/bin/env python2.5 # vim: set fileencoding=utf-8 : for i in xrange ( 3) : print i $ python2.5 PythonTidy.python < test.py #!/usr/bin/python # -*- coding: utf-8 -*- for i in xrange(3): print i About changing the shebang line: I'll take it as a bug. About changing the encoding declaration from vim-style to emacs-style: I'll take it as an insult :) Both are comments, and should be left that way. Besides, there is no officially preferred way for each of them. BTW, in a recent thread on this newsgroup, most people said they preferred #!/usr/bin/env python over #!/usb/bin/python for the shebang line. See http://tinyurl.com/yngmfr . Best regards. -- Roberto Bonvallet From gabor at nekomancer.net Fri Nov 17 05:35:47 2006 From: gabor at nekomancer.net (gabor) Date: Fri, 17 Nov 2006 11:35:47 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > gabor wrote: > >> get an Unicode-exception, as everywhere else. you see, exceptions are >> ok, i can deal with them. > >> p.s: one additional note. if you code expects os.listdir to return >> unicode, that usually means that all your code uses unicode strings. >> which in turn means, that those filenames will somehow later interact >> with unicode strings. which means that that byte-string-filename will >> probably get auto-converted to unicode at a later point, and that >> auto-conversion will VERY probably fail > > it will raise an exception, most likely. didn't you just say that > exceptions were ok? yes, but it's raised at the wrong place imho :) (just to clarify: simply pointing out this behavior in the documentation is also one of the possible solutions) for me the current behavior seems as if file-reading would work like this: a = open('foo.txt') data = a.read() a.close() print data >>> TheFileFromWhichYouHaveReadDidNotExistException gabor From inq1ltd at verizon.net Thu Nov 16 01:28:57 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Thu, 16 Nov 2006 01:28:57 -0500 Subject: Press button to load data In-Reply-To: <1163650825.563379.38550@b28g2000cwb.googlegroups.com> References: <1163650825.563379.38550@b28g2000cwb.googlegroups.com> Message-ID: <200611160128.57425.inq1ltd@verizon.net> Just from a glance my thoughts are to start with one file and build on it. Make a class of it so you can loop it to use it over for each record. You wrote that the info was in a file on the hd. If it is in a file on the hd, use the open() function, read from the file, only one record and write the data to a list. You can incorporate the button option, "command = CallSomeFunction", to call a function that builds a window, and loads the data into labels or entry boxes. If you are going to modify the data, entry boxes allow you to modify it and save it back to a file. Also, when using the open() function, close it after you get the data you need. otherwise you may experience unexpected problems. client = open('client', 'r') client.read() (readline()) (readlines()) client.close() jim-on-linux http//:www.inqvista.com On Wednesday 15 November 2006 23:20, gilbert3b2g at msn.com wrote: > I'm new to Python, and programming in general. > What I'm trying to do here is to load a list of > accounts from a file on my harddrive into a > string of Buttons in Tkinter, and when I press > one of the Buttons, which has one of my account > name, it will load that account into a new > window. But I don't understand how to code the > proccess that would tell the program what > account is selected. Any help with this would > be very appreciated. Thanks in advance. > > from Tkinter import * > import shelve > from tkMessageBox import showerror > > shelvename = shelve.open('class-shelve2') > cat = (' Name ', ' Account # ', ' Amount Due ', > ' Date Due ') > > def NameFields(top): > name1 = Label(None, text=cat[0], > relief=RIDGE, width=20, fg='blue', bg='white', > font=('bold',15)) > name2 = Label(None, text=cat[1], > relief=RIDGE, width=15, fg='blue', bg='white', > font=('bold',15)) > name3 = Label(None, text=cat[2], > relief=RIDGE, width=15, fg='blue', bg='white', > font=('bold',15)) > name4 = Label(None, text=cat[3], > relief=RIDGE, width=15, fg='blue', bg='white', > font=('bold',15)) > name1.grid(row=0, column=0, sticky=NSEW) > name2.grid(row=0, column=1, sticky=NSEW) > name3.grid(row=0, column=2, sticky=NSEW) > name4.grid(row=0, column=3, sticky=NSEW) > top.columnconfigure(0, weight=1) > top.columnconfigure(1, weight=1) > top.columnconfigure(2, weight=1) > top.columnconfigure(3, weight=1) > > > def DisplayBills(top): > c=0 > for bill in shelvename: > bill1 = Button(None, text= > shelvename[bill].name, font=('bold',10), > command=fetchRecord) bill2 = Label(None, text= > shelvename[bill].account, relief=RIDGE, > font=('bold',10)) > bill3 = Label(None, text= > shelvename[bill].paymentDue, relief=RIDGE, > font=('bold',10), fg='red') bill4 = Label(None, > text= shelvename[bill].dateDue, relief=RIDGE, > font=('bold',10)) > bill1.grid(row=c, column=0, > sticky=NSEW) bill2.grid(row=c,column=1, > sticky=NSEW) bill3.grid(row=c,column=2, > sticky=NSEW) bill4.grid(row=c,column=3, > sticky=NSEW) c = c + 1 > > def fetchRecord(): > > top = Tk() > > DisplayBills(top), NameFields(top) > > mainloop() From inq1ltd at verizon.net Mon Nov 20 18:31:26 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Mon, 20 Nov 2006 18:31:26 -0500 Subject: OODB vs RDBMS In-Reply-To: <45621a57$0$10443$426a74cc@news.free.fr> References: <4se3omFv6reaU1@mid.individual.net> <45621a57$0$10443$426a74cc@news.free.fr> Message-ID: <200611201831.26629.inq1ltd@verizon.net> On Monday 20 November 2006 16:34, Bruno Desthuilliers wrote: > Thomas Guettler a ?crit : > > Hi, > > (snip lot of questions about OR mappers) > > http://www.sqlalchemy.org/ Thanks, Verry interesting. jim-on-linux http://www.inqvista.com From userprogoogle-139 at yahoo.co.uk Wed Nov 15 04:24:43 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 15 Nov 2006 01:24:43 -0800 Subject: CORBA: Fnorb Problems References: <1163430997.532317.206850@b28g2000cwb.googlegroups.com> <1163506422.556251.12250@h54g2000cwb.googlegroups.com> Message-ID: <1163582683.646470.67850@k70g2000cwa.googlegroups.com> Thanks the fix you provided me with workds perfectly. Best, rod From dale at riverhall.nospam.co.uk Wed Nov 22 09:20:16 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Wed, 22 Nov 2006 14:20:16 +0000 Subject: What's going on here? Message-ID: 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. >>> a = object() >>> a >>> a.spam = 1 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute 'spam' >>> class b(object): ... pass ... >>> a = b() >>> a <__main__.b object at 0xb7b4dcac> >>> a.spam = 1 >>> What is subclassing adding to the class here? Why can't I assign to attributes of an instance of object? -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From walterbyrd at iname.com Fri Nov 17 12:07:27 2006 From: walterbyrd at iname.com (walterbyrd) Date: 17 Nov 2006 09:07:27 -0800 Subject: Python v PHP for web, and restarting Apache? Message-ID: <1163783247.077263.8590@j44g2000cwa.googlegroups.com> I think I have read somewhere that using Python to develop web-applications requires some restarting of the Apache server, whereas PHP does not. Also, I seem to remember reading something about PHP being able to recover from Apache restarting more easily than Python. I am not trying to suggest anything here. I'm just asking. From thunderfoot at gmail.com Fri Nov 17 10:02:00 2006 From: thunderfoot at gmail.com (thunderfoot at gmail.com) Date: 17 Nov 2006 07:02:00 -0800 Subject: How to pass an argument to a python program open in IDLE? References: <1163611493.817940.299130@f16g2000cwb.googlegroups.com> <1163772388.931433.129480@f16g2000cwb.googlegroups.com> Message-ID: <1163775720.534373.116330@j44g2000cwa.googlegroups.com> TonyHa wrote: > Hello Josh, > > Thanks for the reply. But I am not sure I understand your reply, may be > I need to explain my problem a bit more. I have a Python script which > needs an input argument to run. > e.g. python myscript.py xilinx. which run fine. > > My problem is this: When I start IDLE GUI, then I open my script with > the edit window. (i.e. > File -> open). I run my script under the edit window using run -> run > module or F5. But IDLE does not allow me to input the argument to my > script, i.e. IDLE runs without prompting for the argument, then my > script fails. I wonder how can I pass the argument to my script under > IDLE? > > Tony Ha. > Just check the number of arguments and prompt if the argument is missing: import sys if __name__ == '__main__': numArgs = len(sys.argv) if numArgs == 1: myArg = raw_input('please supply missing argument: ') else: myArg = sys.argv[1] print 'argument : %s' % myArg From 120psi at gmail.com Fri Nov 24 10:25:42 2006 From: 120psi at gmail.com (120psi at gmail.com) Date: 24 Nov 2006 07:25:42 -0800 Subject: Local variables persist in functions? In-Reply-To: References: <1164355869.607182.278200@l12g2000cwl.googlegroups.com> Message-ID: <1164381942.446901.166860@j72g2000cwa.googlegroups.com> > http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects Thanks for the link. I think I'll stick to None as the default value, as that's a good way to keep the usability and make my code work ;) From george.sakkis at gmail.com Tue Nov 21 15:03:11 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 21 Nov 2006 12:03:11 -0800 Subject: Why is class decorator on method loosing self? References: <1164135863.270437.80340@b28g2000cwb.googlegroups.com> <1164138933.778974.42620@f16g2000cwb.googlegroups.com> Message-ID: <1164139391.883659.144770@m7g2000cwm.googlegroups.com> George Sakkis wrote: > Now you don't need memoizefunction and memoizemethod, but you still > need the customized metaclass (changed __customize to _customize; name > turns to a PITA sooner or later): There was supposed to be a "mangling" after "name" (see, it's hard to even spell it out correctly, let alone use it ). George From steve at REMOVE.THIS.cybersource.com.au Mon Nov 6 20:21:27 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 07 Nov 2006 12:21:27 +1100 Subject: forwarding *arg parameter References: <6pn3h.125$7b6.98@read3.inet.fi> <2Fp3h.195$7b6.100@read3.inet.fi> <%oG3h.107$8a7.65@read3.inet.fi> Message-ID: On Mon, 06 Nov 2006 13:03:55 +0000, Tuomas wrote: > If you read the whole chain you find out what we were talking of. I had already read the whole thread, and I've read it again in case I missed something the first time, and I still have no idea why you think you need to do this. You explain *what* you want to do, but not *why* you want to do it. -- Steven. From g.brandl-nospam at gmx.net Mon Nov 6 16:06:53 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 06 Nov 2006 22:06:53 +0100 Subject: Unicode/ascii encoding nightmare In-Reply-To: <1162842650.780517.180360@b28g2000cwb.googlegroups.com> References: <1162842650.780517.180360@b28g2000cwb.googlegroups.com> Message-ID: Thomas W wrote: > I'm getting really annoyed with python in regards to > unicode/ascii-encoding problems. > > The string below is the encoding of the norwegian word "f?dselsdag". > >>>> s = 'f\xc3\x83\xc2\xb8dselsdag' Which encoding is this? > I stored the string as "f?dselsdag" but somewhere in my code it got You stored it where? > translated into the mess above and I cannot get the original string > back. It cannot be printed in the console or written a plain text-file. > I've tried to convert it using > >>>> s.encode('iso-8859-1') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: > ordinal not in range(128) Note that "encode" on a string object is often an indication for an error. The encoding direction (for "normal" encodings, not special things like the "zlib" codec) is as follows: encode: from Unicode decode: to Unicode (the encode method of strings first DEcodes the string with the default encoding, which is normally ascii, then ENcodes it with the given encoding) >>>> s.encode('utf-8') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: > ordinal not in range(128) > > And nothing helps. I cannot remember hacing these problems in earlier > versions of python and it's really annoying, even if it's my own fault > somehow, handling of normal characters like this shouldn't cause this > much hassle. Searching google for "codec can't decode byte" and > UnicodeDecodeError etc. produces a bunch of hits so it's obvious I'm > not alone. Unicode causes many problems if not used properly. If you want to use Unicode strings, use them everywhere in your Python application, decode input as early as possible, and encode output only before writing it to a file or another program. Georg From bignose+hates-spam at benfinney.id.au Sat Nov 11 14:22:02 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 12 Nov 2006 06:22:02 +1100 Subject: handling many default values References: Message-ID: <87mz6xiyat.fsf@benfinney.id.au> "Alan Isaac" writes: > There are *many* parameters, and the list can change, so I want to > avoid listing them all in the Param class's __init__ function, using > the strategy above. > > Q1: Is this approach reasonable? > (This is a newbie question about unforseen hazards.) > Q2: Is it horrible design to isolate the parameters in a separate class? > (Comment: currently several classes may rely on (parts of) the same > parameter set.) It's a bad design smell to have functions that accept large numbers of parameters, many of them optional. Such an interface is difficult to document, maintain and test. You should certainly be examining such code and seeing how much of it can be implemented instead as functions with small, well-defined parameter lists. This may mean writing more functions, or more layers of functions, or more classes, or whatever; but having a result that uses small, well-defined interfaces is a valuable property. -- \ "The number of UNIX installations has grown to 10, with more | `\ expected." -- Unix Programmer's Manual, 2nd Ed., 12-Jun-1972 | _o__) | Ben Finney From orsenthil at gmail.com Mon Nov 13 07:00:32 2006 From: orsenthil at gmail.com (Phoe6) Date: 13 Nov 2006 04:00:32 -0800 Subject: httplib.InvalidURL: nonnumeric port: For characters in the proxy password in URL In-Reply-To: References: <1163408210.915911.327430@k70g2000cwa.googlegroups.com> Message-ID: <1163419232.632721.192360@i42g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Phoe6 wrote: > > Hi, > > The following piece of code works properly when my proxy password > > contains characters[a-zA-Z0-9] etc. But when my proxy password > > contained something like '|\/|' , the httplib incorrectly indentified > > it as separator. > > if you want to prevent the URI parser from treating something as part of > the URI, you need to quote it: > > pwd = urllib.quote(pwd, "") Tried this and did not work out. It ended up confusing urllib and urllib2 objects. I dont want to import urllib, with the urllib2 itself wanted to work around this piece of code. proxy_user = r'senthil_or' proxy_password='|\/|pr0c' #proxy_password = r'|\/|pr0c' # Setup the Proxy with urllib2 proxy_url = r'http://' + proxy_user + ':' + proxy_password + '@' + PROXY_IP proxy_support = urllib2.ProxyHandler({"http":proxy_url}) opener = urllib2.build_opener(proxy_support,urllib2.HTTPHandler) urllib2.install_opener(opener) Thanks, Senthil From gagsl-py at yahoo.com.ar Tue Nov 7 01:50:44 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 07 Nov 2006 03:50:44 -0300 Subject: using split function In-Reply-To: <1162874295.593635.273260@i42g2000cwa.googlegroups.com> References: <1162874036.351559.263280@i42g2000cwa.googlegroups.com> <1162874295.593635.273260@i42g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061107033952.04980410@yahoo.com.ar> > > I have to write a code in python to read a matrix from a text file and > > for that i am using following code. But it gives an error saying > > "NameError: name 'split' is not defined". Can anyone help me with this. A few hints: - don't use "file" as a name - it shadows the builtin "file" type - matrix.close() won't work, perhaps you meant file.close()? > > ----------------------------------------------------- > > Also, i want to initialize the matrix A by zeros, but using A=zeros([4, > > 4]) was giving a similar error "NameError: name 'zeros' is not > > defined". Oh, so *that's* why you build it using standard_normal and then overwrite the contents! -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From mike.klaas at gmail.com Sat Nov 4 19:38:07 2006 From: mike.klaas at gmail.com (Klaas) Date: 4 Nov 2006 16:38:07 -0800 Subject: Defaultdict and speed In-Reply-To: <1162629837.024248.94910@h54g2000cwb.googlegroups.com> References: <1162542563.386682.3090@b28g2000cwb.googlegroups.com> <1162616241.354248.70220@f16g2000cwb.googlegroups.com> <1162629837.024248.94910@h54g2000cwb.googlegroups.com> Message-ID: <1162687087.882739.198890@e3g2000cwe.googlegroups.com> bearophileHUGS at lycos.com wrote: > Klaas wrote: > > Benchmarks? > > There is one (fixed in a succesive post) in the original thread I was > referring to: > http://groups.google.com/group/it.comp.lang.python/browse_thread/thread/aff60c644969f9b/ > If you want I can give more of them (and a bit less silly, with strings > too, etc). <> Sorry, I didn't see any numbers. I ran it myself and found the defaultdict version to be approximately twice as slow. This, as you suggest, is the worst case, as you are using integers as hash keys (essentially no hashing cost) and are accessing each key exactly once. > > > (and slowing down other uses of the class) > > All it has to do is to cheek if the default_factory is an int, it's > just an "if" done only once, so I don't think it slows down the other > cases significantly. Once it makes that check, surely it must check a flag or some such every time it is about to invoke the key constructor function? > > especially when the faster alternative is so easy to code. > > The faster alternative is easy to create, but the best faster > alternative can't be coded, because if you code it in Python you need > two hash accesses, while the defaultdict can require only one of them: > > if n in d: > d[n] += 1 > else: > d[n] = 1 How do you think that defaultdict is implemented? It must perform the dictionary access to determine that the value is missing. It must then go through the method dispatch machinery to look for the __missing__ method, and execute it. If you _really_ want to make this fast, you should write a custom distionary subclass which accepts an object (not function) as default value, and assigns it directly. > >If that performance difference matters, > > With Python it's usually difficult to tell if some performance > difference matters. Probably in some programs it may matter, but in > most other programs it doesn't matter. This is probably true for all > the performance tweaks I may invent in the future too. In general, I agree, but in this case it is quite clear. The only possible speed up is for defaultdict(int). The re-write using regular dicts is trivial, hence, for given piece of code is it quite clear whether the performance gain is important. This is not an interpreter-wide change, after all. Consider also that the performance gains would be relatively unsubstantial when more complicated keys and a more realistic data distribution is used. Consider further that the __missing__ machinery would still be called. Would the resulting construct be faster than the use of a vanilla dict? I doubt it. But you can prove me wrong by implementing it and benchmarking it. > > you would likely find more fruitful > > gains in coding it in c, using PyDict_SET > > I've just started creating a C lib for related purposes, I'd like to > show it to you all on c.l.p, but first I have to find a place to put it > on :-) (It's not easy to find a suitable place, it's a python + c + > pyd, and it's mostly an exercise). Would suggesting a webpage be too trite? -Mike From maxime_phan at hotmail.com Mon Nov 20 11:15:47 2006 From: maxime_phan at hotmail.com (maxime_phan at hotmail.com) Date: 20 Nov 2006 08:15:47 -0800 Subject: sending image pil 1.1.5 by network Message-ID: <1164039347.784574.294770@h54g2000cwb.googlegroups.com> Hello everyone, I'm trying to make a webcam software with python, pil library and enet (networking) Now I have in the client my pil image get from webcam, ready to be send by network. I do that: self.peer.send(0, image.tostring(), enet.FLAG_RELIABLE) and I have this error: TypeError: argument 2 must be string without null bytes, not str does someone know what kind of convertion I should do to make it work? in tostring() function the default encoder is "raw", perhaps there is one ok? Thanks in advance From wojciech_mula at poczta.null.onet.pl.invalid Thu Nov 9 14:21:03 2006 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Thu, 9 Nov 2006 19:21:03 +0000 (UTC) Subject: How to choose the right GUI toolkit ? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> Message-ID: Nick Craig-Wood wrote: >> It's very mature, full-featured, and portable, and fairly easy to >> learn as well. > > ...with native look and feel on each platform unlike GTK / TK AFAIK Tk 8 uses platform's native widgets. w. From salvatore.didio at wanadoo.fr Thu Nov 2 14:10:16 2006 From: salvatore.didio at wanadoo.fr (Salvatore) Date: 2 Nov 2006 11:10:16 -0800 Subject: Forum written in Python? In-Reply-To: References: Message-ID: <1162494616.220423.39070@m73g2000cwd.googlegroups.com> Hello, Look at Karrigell, it includes the base of a forum and a blog in is demo Karrigell is a wonderfull pythonic framework. It's simple and efficient. Thanks his author Regards slav0nic a ?crit : > Karlo Lozovina ?????: > > Are there any forum or bulletin board systems written entirely in Python? > > I got sick of PhpBB, mostly because I can't tweak and fiddle with the > > code, since I really don't like PHP and don't know it that well. > > > > I thought of writting my own simple forum software, but if there are > > existing projects out there, I wouldn't mind contributing. So far I found > > out about Pocoo, but it seems to immature right now, I was looking for > > something comparable to PhpBB or IPB? > > > > > Django-based: > http://wiki.woodpecker.org.cn/moin/UliPad > http://zyons.com > > ----------- > http://python.com.ua From sturlamolden at yahoo.no Sat Nov 18 14:45:27 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 18 Nov 2006 11:45:27 -0800 Subject: About alternatives to Matlab In-Reply-To: <1163876220.121691.166740@h54g2000cwb.googlegroups.com> References: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> <1163711343.870829.110030@h48g2000cwc.googlegroups.com> <1163791069.178490.198740@j44g2000cwa.googlegroups.com> <1163876220.121691.166740@h54g2000cwb.googlegroups.com> Message-ID: <1163879127.582231.268420@b28g2000cwb.googlegroups.com> sturlamolden wrote: > God grief. I followed the implementation in Ingrid Daubechies' and Wim > Sweldens' original wavelet lifting paper (J. Fourier Anal. Appl., 4: > 247-269, 1998). If you look at the factorized polyphase matrix for D4 > (which gives the inverse transform), their implementation of the > lifting steps the original paper is incorrect. That is scary. > > A free PDF or PS of the paper is available here: > > http://cm.bell-labs.com/who/wim/papers/factor/index.html Actually its more complicated than that. The PS and the PDF files are different, and only the PS-file is confused. Here is the correct explanation: The factorization of the polyphase matrix is not unique. There are several valid factorizations. Our implementations corresponds to different factorizations of the analysis and synthesis poyphase matrices, and both are in a sence correct, although numerically different. From g.brandl-nospam at gmx.net Tue Nov 21 11:09:09 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 21 Nov 2006 17:09:09 +0100 Subject: Software Compatable with other versions? In-Reply-To: References: Message-ID: Michael Yanowitz schrieb: > Hello: > > I am still using Python 2.4.3, I haven't upgraded yet. > However, I would like to know if my 2.4.3 programs will run > in 2.5 without modification. > Is there any way to test that my software is compatable > with 2.5 (or any other version), without actually installing > that version?: > > I have been told that the .pyc are not compatable. Is it > possible, to convert a 2.4.x .pyc to a 2.5 .pyc? No. Why should there if there's such an easy way to build it from scratch? Georg From jaap at nospaml.com Sun Nov 5 06:00:07 2006 From: jaap at nospaml.com (Jaap) Date: Sun, 05 Nov 2006 12:00:07 +0100 Subject: tips requested for a log-processing script Message-ID: <454dc438$0$14382$e4fe514c@dreader17.news.xs4all.nl> Python ers, As a relatively new user of Python I would like to ask your advice on the following script I want to create. I have a logfile which contains records. All records have the same layout, and are stored in a CSV-format. Each record is (non-uniquely) identified by a date and a itemID. Each itemID can occur 0 or more times per month. The item contains a figure/amount which I need to sum per month and per itemID. I have already managed to separate the individual parts of each logfile-record by using the csv-module from Python 2.5. very simple indeed. Apart from this I have a configuration file, which contains the list of itemID's i need to focus on per month. Not all itemID's are relevant for each month, but for example only every second or third month. All records in the logfile with other itemID's can be ignored. I have yet to define the format of this configuration file, but am thinking about a 0 or 1 for each month, and then the itemID, like: "1 0 0 1 0 0 1 0 0 1 0 0 123456" for a itemID 123456 which only needs consideration at first month of each quarter. My question to this forum is: which data structure would you propose? The logfile is not very big (about 200k max, average 200k) so I assume I can store in internal memory/list? How would you propose I tackle the filtering of relevant/non-relevant items from logfile? Would you propose I use a filter(func, list) for this task or is another thing better? In the end I want to mail the outcome of my process, but this seems straitforward from the documentation I have found, although I must connect to an external SMTP-server. Any tips, views, advice is highly appreciated! Jaap PS: when I load the logfile in a spreadsheet I can create a pivot table which does about the same ;-] but that is not what I want; the processing must be automated in the end with a periodic script which e-mails the summary of the keyfigure every month. From ptmcg at austin.rr._bogus_.com Mon Nov 6 06:06:35 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 06 Nov 2006 11:06:35 GMT Subject: string to list of numbers conversion References: <1162730071.953080.284980@i42g2000cwa.googlegroups.com> Message-ID: <%GE3h.5945$lx6.583@tornado.texas.rr.com> "jm.suresh at no.spam.gmail.com" wrote in message news:1162730071.953080.284980 at i42g2000cwa.googlegroups.com... > Hi, > I have a string '((1,2), (3,4))' and I want to convert this into a > python tuple of numbers. But I do not want to use eval() because I do > not want to execute any code in that string and limit it to list of > numbers. > Is there any alternative way? > > Thanks. > Suresh > Pyparsing comes with an example that parses strings representing lists. Here's that example, converted to parsing only tuples of numbers. Note that this does not presume that tuples are only pairs, but can be any number of numeric values, nested to any depth, and with arbitrary whitespace, etc. This grammar also includes converters by type, so that ints come out as ints, and floats as floats. (This grammar doesn't handle empty tuples, but it does handle tuples that include an extra ',' after the last tuple element.) -- Paul Download pyparsing at http://sourceforge.net/projects/pyparsing/ . from pyparsing import * integer = (Word(nums)|Word('-+',nums)).setName("integer") real = Combine(integer + "." + Optional(Word(nums))).setName("real") tupleStr = Forward().setName("tuple") tupleItem = real | integer | tupleStr tupleStr << ( Suppress("(") + delimitedList(tupleItem) + Optional(Suppress(",")) + Suppress(")") ) # add parse actions to do conversion during parsing integer.setParseAction( lambda toks: int(toks[0]) ) real.setParseAction( lambda toks: float(toks[0]) ) tupleStr.setParseAction( lambda toks: tuple(toks) ) s = '((1,2), (3,4), (-5,9.2),)' print tupleStr.parseString(s)[0] Gives: ((1, 2), (3, 4), (-5, 9.1999999999999993)) From bdesth.quelquechose at free.quelquepart.fr Wed Nov 8 17:51:17 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 08 Nov 2006 23:51:17 +0100 Subject: is this the right way to do subclasses? In-Reply-To: <45522074$0$17101$c3e8da3@news.astraweb.com> References: <45522074$0$17101$c3e8da3@news.astraweb.com> Message-ID: <45525a98$0$32029$426a34cc@news.free.fr> John Salerno a ?crit : > Ok, back to my so-called "game." I'm just curious if I've implemented > the subclasses properly, because it seems like an awful lot of > repetition with the parameters. And again, if I want to add a new > attribute later, I'd have to change a lot of things. I can't help but > get the feeling that I'm doing something very inefficiently. > > Thanks! > > > > class Character(object): > > def __init__(self, name, strength, dexterity, intelligence): > self.name = name > self.health = 10 > self.strength = strength > self.dexterity = dexterity > self.intelligence = intelligence > > > class Fighter(Character): > > def __init__(self, name, strength, dexterity, intelligence): > Character.__init__(self, name, strength, dexterity, intelligence) > self.health += 2 > self.strength += 1 > > > class Thief(Character): > > def __init__(self, name, strength, dexterity, intelligence): > Character.__init__(self, name, strength, dexterity, intelligence) > self.health += 1 > self.dexterity += 1 > > > class Mage(Character): > > def __init__(self, name, strength, dexterity, intelligence): > Character.__init__(self, name, strength, dexterity, intelligence) > self.intelligence += 1 This is correct, and a good first start. Now there's effectively some boilerplate that we could get rid of using the template method pattern: class Character(object): def __init__(self, name, strength, dexterity, intelligence): self.name = name self.health = 10 self.strength = strength self.dexterity = dexterity self.intelligence = intelligence self._post_init() def _post_init(self): pass class Fighter(Character): def _post_init(self): self.health += 2 self.strength += 1 class Thief(Character): def _post_init(self): self.health += 1 self.dexterity += 1 class Mage(Character): def _post_init(self): self.intelligence += 1 HTH From gagsl-py at yahoo.com.ar Fri Nov 10 17:18:10 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 10 Nov 2006 19:18:10 -0300 Subject: service windows avec py2exe In-Reply-To: <1163157344.987173.259940@i42g2000cwa.googlegroups.com> References: <1163157344.987173.259940@i42g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061110191059.00fd09d0@yahoo.com.ar> At Friday 10/11/2006 08:15, DarkPearl wrote: >apres avoir cr?er un service windows avec py2exe, >j'ai ce probleme quand je lance le service : > >voici ce que je trouve dans le journal d'evenement : > >The instance's SvcRun() method failed >: (-2147221020, 'Syntaxe incorrecte', >None, None) Try with a small sample application then adding more functions, to see where it fails. (Pardonnez moi, je ne sais pas assez pour r?pondre en fran?aise) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From fredrik at pythonware.com Wed Nov 1 04:42:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 01 Nov 2006 10:42:56 +0100 Subject: High level csv reader In-Reply-To: References: <1162361464.706313.221590@e64g2000cwd.googlegroups.com> Message-ID: James Stroud wrote: >> Before I go on and reinvent the wheel, is there a generic high level >> wrapper around csv.reader that does all this ? > > There is a csv in the standard library. I'm not sure the "csv" module qualifies as a high-level wrapper around itself, though. From thunderfoot at gmail.com Thu Nov 30 13:21:51 2006 From: thunderfoot at gmail.com (thunderfoot at gmail.com) Date: 30 Nov 2006 10:21:51 -0800 Subject: Automatic increment In-Reply-To: References: Message-ID: <1164910911.554681.158220@h54g2000cwb.googlegroups.com> Gheorghe Postelnicu wrote: > Hi, > > I have a situation of the following type: > > for line in lineList: > for item in line.split() > myArray[counter, itemCounter] > itemCounter = itemCounter + 1 > counter = counter +1 > > Is there a way to get rid of the manual incrementation of the 2 counters? > for counter, line in enumerate(lineList): for itemCounter, item in enumerate(line.split()): myArray[counter, itemCounter] hth, Don From mail at microcorp.co.za Mon Nov 20 09:57:34 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 20 Nov 2006 16:57:34 +0200 Subject: rpncalc-2.5 RPN Calculator for Python References: <1164009539.310173.248620@m7g2000cwm.googlegroups.com><1164010575.812704.120600@f16g2000cwb.googlegroups.com> <1164021728.545537.170920@m7g2000cwm.googlegroups.com> Message-ID: <000301c70d24$b24fb3a0$03000080@hendrik> "Rob Wolfe" wrote: > > Ant wrote: > > > name = u"\u0141ukasiewicz" # Python syntax so we're not completely OT > > > > Lukershavik IIRC. At least that's how I was told it was pronounced (I > > had to say the damn name many times in presentations whilst using his > > algebras to model three-valued logic. Don't know if there were many > > Poles there to criticise mind ;-) ) > > I wasn't there but you certainly deserved the criticism. ;-) > "Lukershavik" sounds horrible. I'm Polish so I know what I'm saying. > But don't worry, I know it's difficult. :) > Closer would be I think: > > Woo as in wood > cu as in cup > sh as in ship > e as in bed > vi as in victim > tch as in catch > > Woocushevitch Thanks - Hendrik From nospam at domain.tld Thu Nov 16 04:54:36 2006 From: nospam at domain.tld (Stephan Kuhagen) Date: Thu, 16 Nov 2006 10:54:36 +0100 Subject: Secure Python References: Message-ID: Fredrik Tolf wrote: > If this doesn't work, might there be some other way to run untrusted > code that I haven't thought of (apart from using O/S-specific stuff like > SECCOMD, of course). There was a module called rexec which tries to give you a restricted environment for executing code. But it seems, that it is not maintained anymore, because there were too much problems with it. It seems, that it is very complicated to get a restricted execution environment without losing too much of Pythons functionality. One question is, what you want to achieve. As another posting in this thread mentioned, you can't get around of denial of service attacks, even in restricted or trusted environments. So I assume, that what you want is something like a sandbox, where specific file actions (deleting files, access to specific part of the FS at all) and some other things can be restricted or forbidden. I think, this should be possible, even for some DOS-Attacks (e.g. restricting the amount of memory that can be used by the script, or the max stack size, depth of recursion limits etc.), but it is a hard job to find all places, where code can break out of your sandbox. For a full load of bad examples, simply have a look at JavaScript... For a IMHO really good implementation of the sandbox idea, have a look at the "safe interp" in Tcl. A short description (and by no mean complete) of the safe interp is to run a second and completely independent interpreter with all possibly dangerous commands completely removed and a one-way-channel to inject commands and scripts into its evaluation loop from the trusted interpreter. Depending on how much faith you have into the untrusted script, you can selectively allow additional commands in the safe interp or map common commands to other restricted or monitored versions of them, which you implemented yourself inside your trusted environment. I do not know, how complex it would be to do this in Python (since Tcl may look a little old fashioned to some people but has some unique features that helps especially with this kind of problem, such as having no keywords, which makes it possible to change the semantics of even the most basic constructs in the language from the scripting level), but I think it would be a really useful feature for Python to have a sandbox mechanism to run untrusted code. Regards Stephan From klaus at seistrup.dk Wed Nov 1 00:08:13 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Wed, 1 Nov 2006 05:08:13 +0000 (UTC) Subject: Unescape HTML entities References: Message-ID: Rares Vernica wrote: > How does your code deal with ' like entities? It doesn't, it deals with named entities only. But take a look at Fredrik's example. Cheers, -- Klaus Alexander Seistrup K?benhavn, Danmark, EU http://klaus.seistrup.dk/ From kai.kuehne at gmail.com Sat Nov 18 17:06:32 2006 From: kai.kuehne at gmail.com (Kai Kuehne) Date: Sat, 18 Nov 2006 23:06:32 +0100 Subject: Overwrite only one function with property() Message-ID: Hi list! It is possible to overwrite only one function with the property-function? x = property(getx, setx, delx, 'doc') I just want to overwrite setx, but when I set the others to None, I can't read and del the member. Any ideas or is this not possible? Thank you! Kai From fredrik at pythonware.com Thu Nov 23 10:47:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Nov 2006 16:47:00 +0100 Subject: select() on WinXP References: <1164296300.268074.250230@j44g2000cwa.googlegroups.com> Message-ID: grebekel at gmail.com wrote: > I'm running Python 2.5 on Windows XP. When I try to do this: > > [code] > import select > select.select([], [], []) > [/code] > > I get this: > > [output] > Traceback (most recent call last): > File "C:/Documents and Settings/Grebekel/Desktop/s.py", line 2, in > > select.select([],[],[]) > error: (10022, 'An invalid argument was supplied') > [/output] > > Is there anything I should be aware of to get select() working under > Windows? like, say, only calling select if you actually have something you want to select on? (if you want to sleep, use time.sleep()) From no-spam at no-spam-no-spam.invalid Sat Nov 4 07:20:23 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sat, 04 Nov 2006 13:20:23 +0100 Subject: py2exe questions In-Reply-To: References: <454BB574.9030607@websafe.com> Message-ID: Thomas Heller wrote: > Larry Bates schrieb: >> Doug Stell wrote: >>> I have 2 questions about py2exe or any similar utility. >>> >>> 1. Is it possible to create a single Windows executable that does not >>> blow out to a folder full of files and can be called from scripts >>> using command line arguments? >>> >>> 2. If the above can be done, it is possible to hide parts of the >>> Python source code from users? These users are software developers, >>> but we don't want them to see how the code does what it does. >>> >>> thanks, doug >> py2exe reduce the number of files you need to distribute down to 4: >> >> msvcr71.dll >> w9xpopen.exe (Windows/98 support) >> library.zip (all .pyo, .pyd, and .dll files) >> applcation.exe > > It can easily be reduced to 2 files by 'embedding' the libray.zip > into the exe (use the zipfile=None option), and deleting the w9xpopen.exe > if you don't need win98 support. and finally you can use Python2.3 to avoid msvcr71.dll -robert From antroy at gmail.com Thu Nov 2 10:52:40 2006 From: antroy at gmail.com (Ant) Date: 2 Nov 2006 07:52:40 -0800 Subject: creating new objects with references to them In-Reply-To: <1162480549.786082.290980@b28g2000cwb.googlegroups.com> References: <1162480549.786082.290980@b28g2000cwb.googlegroups.com> Message-ID: <1162482760.424782.244760@h48g2000cwc.googlegroups.com> On Nov 2, 3:15 pm, "JohnJSal" wrote: > It seems like what I want to do is something that programmers deal with > everyday, but I just can't think of a way to do it. Basically, I am > writing a DB front-end and I want a new "Researcher" object to be > created whenever the user presses the "New Record" button. He can open > as many new records at a time as he wants and fill in the information. > > What I don't know how to do is handle this arbitrary number of objects. > When it comes time to save the data to the DB, how do I access each > object (to get the text fields associated with each)? Won't I have to > have given each instance some name? It all depends on what UI you are using (Web frontend? GUI such as Tkinter?) and what your use case is. What is it exactly that you want to do? Create a bunch of Researcher objects and then save them in a single hit? Create a list of Researchers and then choose which to save to the db? Populate a list of researchers from the db, and have the option of editing or adding new ones? Should the new Researcher objects be committed to the db as soon as they are saved? Anyway, a simple list of Researchers should suffice for any of these purposes, and assuming you want to commit them all in one hit, you have a list of objects ready to iterate over. From 120psi at gmail.com Fri Nov 24 11:12:08 2006 From: 120psi at gmail.com (120psi at gmail.com) Date: 24 Nov 2006 08:12:08 -0800 Subject: synching with os.walk() References: Message-ID: <1164384728.336225.59840@l39g2000cwd.googlegroups.com> > os.walk() is a nice generator for performing actions on all files in a > directory and subdirectories. However, how can one use os.walk() for walking > through two hierarchies at once? I want to synchronise two directories (just > backup for now), but cannot see how I can traverse a second one. I do this > now with os.listdir() recursively, which works fine, but I am afraid that > recursion can become inefficient for large hierarchies. I've run into wanting to work with parallel directory structures before, and what I generally do is something like: for root, dirs, files in os.walk( dir1 ): dir2_root = dir2 + root[len(dir1):] for f in files: dir1_path = os.path.join( root, f ) dir2_path = os.path.join( dir2_root, f ) Does this work for your needs? -- Nils From sjmachin at lexicon.net Thu Nov 9 02:49:23 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Nov 2006 23:49:23 -0800 Subject: which is a good imaging lib in python?? In-Reply-To: <1163057897.010765.46780@h48g2000cwc.googlegroups.com> References: <1163057897.010765.46780@h48g2000cwc.googlegroups.com> Message-ID: <1163058562.951043.167910@i42g2000cwa.googlegroups.com> srj wrote: > hi > can any1 tell me which is a good imaging lib in python and where i can > get it (2 dwnld) from?? > > regds The straight answer to your question is "Yes". If you were to do a google search for "python imaging library", you would then be in a position to tell yourself. From mnations at gmail.com Sat Nov 4 11:23:40 2006 From: mnations at gmail.com (Mudcat) Date: 4 Nov 2006 08:23:40 -0800 Subject: python GUIs comparison (want) In-Reply-To: <453E3370.9060008@kevin-walzer.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> Message-ID: <1162657420.655675.185930@e3g2000cwe.googlegroups.com> I have been using Tkinter for several years now. Recently I have been thinking about switching to something else that may have a sharper appearance. However I'm not sure what that may be, and if that something else is *that* much better than what I'm already using. Does everyone agree that wxPython looks best on Windows? I've also read in a couple of places where Dabo looks pretty good as well. So if someone were to pick a UI that gave the best appearance, what would they choose? Kevin Walzer wrote: > jiang.haiyun at gmail.com wrote: > > Now i began to learn GUI programming. There are so many > > choices of GUI in the python world, wxPython, pyGTK, PyQT, > > Tkinter, .etc, it's difficult for a novice to decide, however. > > Can you draw a comparison among them on easy coding, pythonish design, > > beautiful and generous looking, powerful development toolkit, and > > sufficient documentation, .etc. > > It's helpful for a GUI beginner. > > Thank you. > > > > > > :)Sorry for my poor english. > > > > Tkinter: > Pro: Default GUI library for Python; stable; well-supported > Con: Needs extension for complex/rich GUI's; core widgets are dated in > look and feel; many modern extensions in Tcl/Tk have not made it into > Tkinter or are not widely used (Tile, Tablelist) > > wxPython: > Pro: Popular, actively developed, wraps native widgets, looks great on > Windows, commercial-friendly license > Con: Based on C++ toolkit; docs assume knowledge of C++; some think > coding style is too much like C++; complex to build and deploy on Linux > (wraps Gtk) > > PyQt: > Pro: Powerful, cross-platform, sophisticated GUI's > Con: Based on C++ toolkit; docs assume knowledge of C++; commercial > deployment is expensive; free deployment must be GPL; smaller > development and user community than wxPython > > PyGtk: > Pro: Sophisticated GUI's, cross-platform (Linux and Win32); very popular > on some platforms; active development community > Con: Not native on OS X > > > > > > -- > Kevin Walzer > Code by Kevin > http://www.codebykevin.com From acatejr at gmail.com Fri Nov 3 18:30:14 2006 From: acatejr at gmail.com (acatejr at gmail.com) Date: 3 Nov 2006 15:30:14 -0800 Subject: Python Classes and dynamic class members Message-ID: <1162596614.073100.54850@e3g2000cwe.googlegroups.com> I have a text file that I am parsing. Each line is of the form: max_time 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10 0.11 0.12 The first item is the field name and the next twelve items are values for each month in the year. There are multiple lines each for some different variable. I am able to parse this data easily enough, but what I'd like to do is have a class that stores all this infomormation using dynamic member attributes/fields and the resulting list of values. For example, if the class WeatherData was instantiated and I parsed the line above as so: field_name = "max_time; values = [0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.10,0.11,0.12] how could I get weather data to store values in an attribute called "max_time"? Ultimately, something like this would be possible: >>>WeatherData.max_time >>>[0.01,0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.09,0.10,0.11,0.12] Any help would be appreciated. From fredrik at pythonware.com Tue Nov 14 06:10:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Nov 2006 12:10:35 +0100 Subject: PyFAQ: help wanted with thread article Message-ID: this FAQ item talks about using sleep to make sure that threads run properly: http://effbot.org/pyfaq/none-of-my-threads-seem-to-run-why.htm I suspect it was originally written for the "thread" module, but as far as I know, the "threading" module takes care of the issues described here all by itself. so, should this item be removed? or can anyone suggest a rewrite that's more relevant for "threading" users. feel free to post suggestions (or better, an updated text) to this thread, or over at the PyFAQ staging site. From johnjsal at NOSPAMgmail.com Mon Nov 6 16:56:41 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 06 Nov 2006 16:56:41 -0500 Subject: sqlite error? In-Reply-To: <1162849478.092439.297160@i42g2000cwa.googlegroups.com> References: <454fa4dc$0$6987$c3e8da3@news.astraweb.com> <1162849478.092439.297160@i42g2000cwa.googlegroups.com> Message-ID: <454faf0a$0$12993$c3e8da3@news.astraweb.com> thunderfoot at gmail.com wrote: > John Salerno wrote: >> Am I using the ? placeholder wrong in this example? >> >> >> t = ('hi', 'bye') >> >> self.connection.execute("INSERT INTO Personal (firstName, lastName) >> VALUES ?", t) >> >> >> >> Traceback (most recent call last): >> File "C:\Python25\myscripts\labdb\dbapp.py", line 93, in OnSaveRecord >> self.save_to_database(textfield_values) >> File "C:\Python25\myscripts\labdb\dbapp.py", line 97, in save_to_database >> self.connection.execute("INSERT INTO Personal (firstName, lastName) >> VALUES ?", t) >> sqlite3.OperationalError: near "?": syntax error > > I believe you're missing the parens around your VALUES to insert. Also, > you need 1 placeholder per argument inserted, not just one for the > entire argument list. Try: > > self.connection.execute("INSERT INTO Personal (firstName, lastName) > VALUES (?, ?)", t) > > HTH > Thanks guys. I'll try this. I thought the ? stood for the whole tuple. From ynaddaf at riptown.com Tue Nov 7 17:16:53 2006 From: ynaddaf at riptown.com (deLenn) Date: 7 Nov 2006 14:16:53 -0800 Subject: Finding Nonzero Elements in a Sparse Matrix Message-ID: <1162937813.360645.3040@h54g2000cwb.googlegroups.com> Hi, Does scipy have an equivalent to Matlab's 'find' function, to list the indices of all nonzero elements in a sparse matrix? Cheers. From st911 at rock.com Thu Nov 30 19:49:12 2006 From: st911 at rock.com (st911 at rock.com) Date: 30 Nov 2006 16:49:12 -0800 Subject: *** 911 WAS AN INSIDE JOB. YOU WILL GET ALL SCIENTIFIC EVIDENCE ON st911.org *** Message-ID: <1164934152.400086.196120@n67g2000cwd.googlegroups.com> 911 WAS AN INSIDE JOB. YOU WILL GET ALL SCIENTIFIC EVIDENCE ON st911.org The written apology reads: "The United States of America apologizes to Mr. Brandon Mayfield and his family for the suffering caused by the FBI's misidentification of Mr. Mayfield's fingerprint and the resulting investigation of Mr. Mayfield, including his arrest as a material witness in connection with the 2004 Madrid train bombings and the execution of search warrants and other court orders in the Mayfield family home and in Mr. Mayfield's law office." He and his family later sued the U.S. government for damages. "We lived in 1984," Mayfield told reporters Wednesday. "I'm talking about the George Orwell, frightening brave new world in which Big Brother is constantly watching you." (Watch Mayfield discuss the case Video) "I, myself, have dark memories of stifling paranoia, of being monitored, followed, watched, tracked," he said, choking back emotion. "I've been surveilled, followed, targeted primarily because I've been an outspoken critic of this administration and doing my job to defend others who can't defend themselves, to give them their day in court, and mostly for being a Muslim." The government refused, he said, to tell him where they put their cameras and surveillance devices, leaving his family wondering if their private conversations and intimate moments were on display. "The days and weeks and months following my arrest were some of the hardest and darkest that myself and my family have ever had to endure," he said. "And all because of this government's ill-conceived war on terror. ... What I really want is for this not to happen to anyone else." Wednesday's settlement includes not only a $2 million payment and an apology, but also an agreement by the government to destroy communications intercepts conducted by the FBI against Mayfield's home and office during the investigation. The written apology reads: "The United States of America apologizes to Mr. Brandon Mayfield and his family for the suffering caused by the FBI's misidentification of Mr. Mayfield's fingerprint and the resulting investigation of Mr. Mayfield, including his arrest as a material witness in connection with the 2004 Madrid train bombings and the execution of search warrants and other court orders in the Mayfield family home and in Mr. Mayfield's law office." A Justice Department statement released Wednesday said Mayfield was not targeted because of his Muslim faith and that the FBI had taken steps to improve its fingerprint identification process "to ensure that what happened to Mr. Mayfield does not happen again." "Mr. Mayfield and his family felt it was in their best interest to get on with their lives," said Mayfield's attorney, Elden Rosenthal. "No amount of money can compensate Mr. Mayfield for being held as a prisoner and being told he faced the death penalty [for the Madrid bombings]." Mayfield said his suit was not about money. "It's about regaining our civil rights, our freedom and most important, our privacy," he said. He and his attorneys said the settlement will allow him to continue the portion of his lawsuit challenging the constitutionality of the Patriot Act. Mayfield contends that his home was searched under provisions of the Patriot Act. ==================================================================== Criminal, Rogue and RACIST elements have penetrated all the branches of USA and world governments. We know that on 911 FBI bastards ran all over in the neighborhood of Pentagon trying to confiscate EVIDENCE of the 911 crime that no Boeing Passenger Airliner hit Pentagon. They have stil not released the evidence. 911 was inside job. FBI is the BEST of the criminal branches ... THERE ARE MORE EVIL AND BIGGER ROGUES IN CIA, NSA, Mossad, PENTAGON AND THE WHITE HOUSE. Dont forget that BASTARD, NIXON and JOHNSON who sank USS LIBERTY and KILLED AMERICANS with the help of ISRAEL ... FBI is the BEST of the criminal branches ... THERE ARE MORE EVIL AND BIGGER ROGUES IN CIA, NSA, PENTAGON AND THE WHITE HOUSE. Dont forget that BASTARD, NIXON and JOHNSON who sank USS LIBERTY and KILLED AMERICANS with the help of ISRAEL ... THE ONLY ONLY REASON FBI DID THIS IS BECAUSE THEIR CRIME WAS UNCONCEALABLE. UNDER THE PRETEXT OF SELF-DEFENSE, MANY OF THESE AGENCY OFFICIALS HAVE COVERED THEIR CRIMES AND DESTROYED EVIDENCE OF THEIR CRIMES. FBI COVERED UP A CHILD PEDOPHILIA RING THAT WAS LINED TO REAGAN AND HERBERT WALKER BUSH. There is a VIDEO on google of the investigation. =========================== www.nkusa.org Name: www.nkusa.org Nickname: www.st911.org Location: WTC Building 7 Title: Pentagon Videos Industry: Non-Profit Email address: s... at rock.com Website or Blog: www.infowars.com www.prisonplanet.org www.counterpunch.org Quote: On 911, the only buildings that were demolished were the ones that belonged to Larry Silverstein. Building 7 Committed suicide even though no plane had hit it. Within minutes, FBI bastards were running around confiscating the pentagon videos to coverup the fact that there was no plane that hit the pentagon. Every bastard in the plot spoke in passive language: Rudy Guiliani said ... we were told ... WHO TOLD YOU!!! The physics shows that the building were demolished by synchronized explosions. Residue of Thermate = Thermite + Sulfur have been found in the molten metal pools. The time of fall is equal to free fall, debunking the pancake theory. Uncontrolled burning of Jet fuel does not create molten metal pools. View the videos with your own eyeballs. On the next day the uncivilized mad dogs of europe stood up and barked that an attack on one country is on all of them, becoming infact the most effective enablers of the actual criminals of 911. Instead of a dispassionate investigation they barked for war. This led to invasion of Afghanistan, the false cooked evidence of WMDs on Iraq. The use of white phosphorus, war crime. The naked human towers. The mad dogs of europe in the govt are all quiet on this. Only humane civilians of europe are vocal and making their efforts at individual levels. From fredrik at pythonware.com Tue Nov 28 02:22:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 28 Nov 2006 08:22:54 +0100 Subject: Inheritance from builtin list and override of methods. In-Reply-To: References: <200611261804.54669.mgiann@beta-cae.gr> <200611271133.48359.mgiann@beta-cae.gr> Message-ID: OKB (not okblacke) wrote: > Why doesn't it? because whoever wrote the class didn't do things that way, mostly for efficiency reasons. there's nothing in Python that keeps you from using template methods if you want, but that's a costly approach, so it's not very common. I suggest reading up on OO design patterns. From vatamane at gmail.com Sun Nov 5 03:42:23 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 5 Nov 2006 00:42:23 -0800 Subject: NEWBIE: Script help needed References: Message-ID: <1162716143.747535.109270@h48g2000cwc.googlegroups.com> If the other commands work but 3) doesn't, it means there is something different (wrong?) with the command. So try running 3) , then one of the other ones and see the difference. The getCommandOutput() , I suspect, just waits for the data from the actual command and the command is not returning anything. It could be because it just takes way too long (I am not familiar with Gentoo, so not sure if emerge world takes 1 second or 24 hours...) or perhaps the "emerge -uvp world" stops at some point and is waiting for input (a command prompt like "are you sure you want to do this [Y/n]?" For more in depth on subprocesses in Python take a look at the subprocess module: http://docs.python.org/lib/module-subprocess.html Hope this helps, Nick V. Lorenzo wrote: > I have this script that I want to use weekly to send me email with > information regarding disk space and available upgrades for my system. > This script is actually a learning tool for me as I learn Python. The > problem I've run into has me stumped and I need some help. What happens > is when the script runs it does these things, parses the result and > appends that to an html string: > > 1) checks disk space by using df -t reiserfs > 2) runs time emerge --sync > 3) runs emerge -uvp world > 4) runs emerge -uv --fetchonly world > > The 'emerge' command is a Gentoo specific one. If I remove step 3), > everything else runs just fine, the email is sent and I receive what I > expect. But when step 3) is allowed to run, even if its the only command > that runs, it hangs somewhere in the function getCommandOutput. If I try > and debug the command, it appears to hang on this line: > err = child.wait() > > I suspect a race condition, but I'm not sure how to proceed, can someone > lend me a hand. Here is the script I wrote, I got the command > getCommandOutput from this site: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52296 > TIA > > [code] > #!/usr/bin/python > > ################################ > ### NEED TO RUN THIS AS ROOT ### > ### EMERGE SYNC REQUIRES THIS ### > ################################ > import os, re, smtplib, MimeWriter, mimetools, cStringIO, popen2, fcntl, > select, pdb > > cmd = 'df -t reiserfs' > finalList = [] > theOutput = [] > > text = "This realy should be in HTML" > > > html = "\ > \ > charset=iso-8859-1\">\ > \ >
Disk Utilization on > Hedley:
" > > out = cStringIO.StringIO() > writer = MimeWriter.MimeWriter(out) > txtin = cStringIO.StringIO(text) > > > def createhtmlmail (html, text, subject): > """Create a mime-message that will render HTML in popular > MUAs, text in better ones""" > import MimeWriter > import mimetools > import cStringIO > > out = cStringIO.StringIO() # output buffer for our message > htmlin = cStringIO.StringIO(html) > txtin = cStringIO.StringIO(text) > > writer = MimeWriter.MimeWriter(out) > # > # set up some basic headers... we put subject here > # because smtplib.sendmail expects it to be in the > # message body > # > writer.addheader("Subject", subject) > writer.addheader("MIME-Version", "1.0") > > writer.addheader("From", "Hedley at myserver.com") > writer.addheader("To", "lorenzo at myserver.com") > # > # start the multipart section of the message > # multipart/alternative seems to work better > # on some MUAs than multipart/mixed > # > writer.startmultipartbody("alternative") > writer.flushheaders() > # > # the plain text section > # > subpart = writer.nextpart() > subpart.addheader("Content-Transfer-Encoding", "quoted-printable") > pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) > mimetools.encode(txtin, pout, 'quoted-printable') > txtin.close() > # > # start the html subpart of the message > # > subpart = writer.nextpart() > subpart.addheader("Content-Transfer-Encoding", "quoted-printable") > # > # returns us a file-ish object we can write to > # > pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) > mimetools.encode(htmlin, pout, 'quoted-printable') > htmlin.close() > # > # Now that we're done, close our writer and > # return the message body > # > writer.lastpart() > msg = out.getvalue() > out.close() > print msg > return msg > > def makeNonBlocking(fd): > fl = fcntl.fcntl(fd, fcntl.F_GETFL) > try: > fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY) > except AttributeError: > fcntl.fcntl(fd, fcntl.F_SETFL, fl | fcntl.FNDELAY) > > > def getCommandOutput(command): > theOutput = [] > child = popen2.Popen3(command, 1) # capture stdout and stderr from > command > child.tochild.close() # don't need to talk to child > outfile = child.fromchild > outfd = outfile.fileno() > errfile = child.childerr > errfd = errfile.fileno() > makeNonBlocking(outfd) # don't deadlock! > makeNonBlocking(errfd) > outdata = errdata = '' > outeof = erreof = 0 > while 1: > ready = select.select([outfd,errfd],[],[]) # wait for input > if outfd in ready[0]: > outchunk = outfile.read() > if outchunk == '': outeof = 1 > outdata = outdata + outchunk > if errfd in ready[0]: > errchunk = errfile.read() > if errchunk == '': erreof = 1 > errdata = errdata + errchunk > if outeof and erreof: break > select.select([],[],[],.1) # give a little time for buffers to fill > err = child.wait() > if err != 0: > raise RuntimeError, '%s failed w/ exit code %d\n%s' % (command, err, > errdata) > theOutput.append(outdata) > theOutput.append(errdata) > return theOutput > > > #Run df and get the disk info > output = os.popen(cmd) > > # match two or more spaces, the header line has a sngle > # space between the 'Mouted on' field > # We need to keep those together > # The other spaces are the separation in the field headers > # To get the output from df down to just the field headers > # and the data, we need to match 2 or more spaces > # -1 eliminates the \n at the end of output. > # We'll get it back when we write each line to the > # mail message, I suspect > > html += "" > > for lines in output.readlines(): > > p = re.compile('\ +') > formattedText = p.subn(' ', lines[:-1], 5) > html += formattedText[0] + '
' > > html += "
" > > mydata = getCommandOutput("time emerge --sync") > > > p = re.compile('\ +') > p.subn(' ', mydata[1])[0] > p = re.compile('\n') > string = (p.subn('
', mydata[1]))[0] > > html += "

Sync Time: " + "
" + > "
" + "" + string + "" > > > mydata = "" > mydata = getCommandOutput("emerge -uvp world") > > p = re.compile('\ +') > (p.subn(' ', mydata[0]))[0] > p = re.compile('\n') > html += "" + (p.subn('
', mydata[0]))[0] + > "
" > > > > try: > getCommandOutput('emerge -uv --fetchonly world') > html += "
Fetch completed > successfuly!
" > except RuntimeError: > html += "< font color='Red'>
******Fetch did not complete > successfully!*********" > > html+= ' ' > > out = cStringIO.StringIO() > writer = MimeWriter.MimeWriter(out) > txtin = cStringIO.StringIO("This should be in HTML") > subject = "Emerge info and disk utilization on Hedley" > message = createhtmlmail(html, text, subject) > server = smtplib.SMTP("hedley") > server.sendmail('Hedley at myserver.com', 'lorenzo at myserver.com', message) > server.quit() > [/code] > > -- > "My Break-Dancing days are over, but there's always the Funky Chicken" > --The Full Monty From sjmachin at lexicon.net Thu Nov 30 13:33:36 2006 From: sjmachin at lexicon.net (John Machin) Date: 30 Nov 2006 10:33:36 -0800 Subject: extremely slow array indexing? References: <1164907021.765969.129280@80g2000cwy.googlegroups.com> <1164908923.363433.43770@l39g2000cwd.googlegroups.com> Message-ID: <1164911616.009985.210320@h54g2000cwb.googlegroups.com> Will McGugan wrote: > Grace Fang wrote: > > > Hi, > > > > I am writing code to sort the columns according to the sum of each > > column. The dataset is huge (50k rows x 300k cols), so i need to read > > line by line and do the summation to avoid the out-of-memory problem. > > But I don't know why it runs very slow, and part of the code is as > > follows. I suspect it's because of array index, but not sure. Can > > anyone > > point out what needs to be modified to make it run fast? thanks in > > advance! > > Array indexing is unlikely to be the culprit. Could it not just be > slow, because you are processing a lot of data? With numbers those big > I would expect to have enough time to go make a coffee, then drink it. > > If you think it is slower than it could be, post more code for > optimization advice... > > Will McGugan Hi Grace, What Will McGugan said, plus: 1. Post *much* more of your code e.g. all relevant parts :-) 2. Explain "featureDict" and "componentdict1"; note that you seem to be doing more dictionary accessing than array indexing. 3. Tell us what is "row" (not mentioned elsewhere) in the last line of your code snippet. Should it be "currRow"? For your sake and ours, copy/paste your code; don't re-type it. 4. Tell us what version of Python [why are you using dict.has_key??], what platform, how much memory. 5. Tell us what "very slow" means e.g. how many rows per second. HTH, John From codecraig at gmail.com Wed Nov 1 07:54:32 2006 From: codecraig at gmail.com (abcd) Date: 1 Nov 2006 04:54:32 -0800 Subject: wxPython TextCtrl - weird scrolling behavior In-Reply-To: References: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> <1162238656.661097.75180@f16g2000cwb.googlegroups.com> <1162240822.260735.316040@e64g2000cwd.googlegroups.com> <2yt1h.206$1n3.4433@news.tufts.edu> <1162242161.009063.65140@e64g2000cwd.googlegroups.com> Message-ID: <1162385672.853549.19620@h48g2000cwc.googlegroups.com> thanks for the feedback, I am watching the screencasts, which are helping already. I think I will try out the Dabo GUI tool since it uses wxPython...and see if I can get the code I need from it. thanks From anthra.norell at vtxmail.ch Wed Nov 8 10:24:54 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Wed, 08 Nov 2006 16:24:54 +0100 Subject: Character encoding In-Reply-To: <1162928072.047884.163420@i42g2000cwa.googlegroups.com> References: <1162928072.047884.163420@i42g2000cwa.googlegroups.com> Message-ID: <4551F6C6.70704@vtxmail.ch> mp wrote: > I have html document titles with characters like >,  , and > ‡. How do I decode a string with these values in Python? > > Thanks > > This is definitely the most FAQ. It comes up about once a week. The stream-editing way is like this: >>> import SE >>> HTM_Decoder = SE.SE ('htm2iso.se') # Include path >>> test_string = '''I have html document titles with characters like >,  , and ‡. How do I decode a string with these values in Python?''' >>> print HTM_Decoder (test_string) I have html document titles with characters like >, , and ?. How do I decode a string with these values in Python? An SE object does files too. >>> HTM_Decoder ('with_codes.txt', 'translated_codes.txt') # Include path You could download SE from -> http://cheeseshop.python.org/pypi/SE/2.3. The translation definitions file "htm2iso.se" is included. If you open it in your editor, you can see how to write your own definition files for other translation tasks you may have some other time. Regards Frederic From python at hope.cz Thu Nov 9 04:58:13 2006 From: python at hope.cz (Lad) Date: 9 Nov 2006 01:58:13 -0800 Subject: Sorted list - how to change it In-Reply-To: References: <1163065969.593970.165600@b28g2000cwb.googlegroups.com> Message-ID: <1163066293.423953.292460@m7g2000cwm.googlegroups.com> Wolfram Kraus wrote: > On 09.11.2006 10:52, Lad wrote: > > I have a sorted list for example [1,2,3,4,5] and I would like to change > > it in a random way > > e.g [2,5,3,1,4] or [3,4,1,5,2] or in any other way except being > > ordered. > > What is the best/easiest > > way how to do it? > > > > Thank you for help > > L. > > > use random.shuffel: > > >>> import random > >>> x = [1,2,3,4,5] > >>> random.shuffle(x) > >>> x > [1, 4, 2, 3, 5] > >>> random.shuffle(x) > >>> x > [4, 2, 1, 3, 5] > > see: http://docs.python.org/lib/module-random.html Wolfram, Thanks a lot for help L. From sven.dahlstrand at gmail.com Fri Nov 10 14:58:22 2006 From: sven.dahlstrand at gmail.com (Sven) Date: 10 Nov 2006 11:58:22 -0800 Subject: urlretrieve get file name In-Reply-To: References: <1163110313.580268.19660@h48g2000cwc.googlegroups.com> <1163116359.787681.31490@m73g2000cwd.googlegroups.com> Message-ID: <1163188701.981923.18960@h48g2000cwc.googlegroups.com> Yes the browser suggests a file name, but I did a little research using http://web-sniffer.net/. The Response Header contains roughly this: HTTP Status Code: HTTP/1.1 302 Found Location: http://page.com/filename.zip Content-Length: 0 Connection: close Content-Type: text/html The status code 302 tells the browser where to find the file. The funny thing is that calling the info() function, on the file-like response object, in Python doesn't return the same header. I'm so stuck. :-) Thanks for your help. On 10 Nov, 01:27, Gabriel Genellina wrote: > At Thursday 9/11/2006 20:52, Sven wrote: > > >Thanks for your help, but I'm a guy with no luck. :-) I can't get the > >file name from response header...Try using a browser and "Save as..."; if it suggests a file name, it > *must* be in the headers - so look again carefully. > If it does not suggests a filen ame, the server is not providing one > (there is no obligation to do so). > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! > ?Abr? tu cuenta ya! -http://correo.yahoo.com.ar From bignose+hates-spam at benfinney.id.au Sun Nov 12 23:11:31 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 13 Nov 2006 15:11:31 +1100 Subject: how do i map this? References: <1163387481.135930.167580@m7g2000cwm.googlegroups.com> Message-ID: <87zmawgf4c.fsf@benfinney.id.au> "ronrsr" writes: > #row is a dictionary with keys: zid, keywords, citation, quotation > def print_row(row): > print """ > %(keywords)s > > %(quotation)s > > %(citation)s > >
name="updateform" enctype="application/x-www-form-urlencoded" > method="GET"> type="submit" value="Edit">
> > > """ You're printing a string, and never using that 'row' parameter. Perhaps this will help illustrate: >>> print "spam %(foo)s eggs" spam %(foo)s eggs >>> print "spam %(foo)s eggs" % {'foo': "Wortle"} spam Wortle eggs The 'print' statement doesn't care about the format specifiers; it just wants a string expression. It's the formatting operator, '%', that looks for them. -- \ "When I was little, my grandfather used to make me stand in a | `\ closet for five minutes without moving. He said it was elevator | _o__) practice." -- Steven Wright | Ben Finney From martin at v.loewis.de Fri Nov 10 19:02:55 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 11 Nov 2006 01:02:55 +0100 Subject: Python 2.5 Core Dump on Solaris 8 In-Reply-To: References: Message-ID: <4555132f$0$3586$9b622d9e@news.freenet.de> Melissa Evans schrieb: > I've modified grappy.py, > http://www.stacken.kth.se/~mattiasa/projects/grappy/, a postfix policy > daemon for greylisting. to use LDAP as a backend instead of SQL (with > python-ldap.) The daemon runs fine when testing but when I put it under > load it core dumps quickly. What little analysis I know how to do shows > similar information every time. Any advice on where to go from here? It looks like a memory allocation bug, e.g. caused by a double free, or possibly a buffer overrun. It's unlikely that the Python interpreter itself has such a bug, so it's likely rather caused in an extension module (e.g. the ldap module). Analysing such a problem is tedious. You should create a debug build of Python (which already has some memory checks) and see whether it reports anything. Then, you could try a debug malloc next (such as dmalloc.com). If you have a license, you can use Purify, if not, try Valgrind (not sure whether it runs on Solaris, though). Another such library is ElectricFence. Good luck, Martin From erinhouston at gmail.com Mon Nov 6 23:38:15 2006 From: erinhouston at gmail.com (ina) Date: 6 Nov 2006 20:38:15 -0800 Subject: using split function In-Reply-To: <1162874036.351559.263280@i42g2000cwa.googlegroups.com> References: <1162874036.351559.263280@i42g2000cwa.googlegroups.com> Message-ID: <1162874295.593635.273260@i42g2000cwa.googlegroups.com> amitsoni.1984 at gmail.com wrote: > Hi, > > I have to write a code in python to read a matrix from a text file and > for that i am using following code. But it gives an error saying > "NameError: name 'split' is not defined". Can anyone help me with this. > ------------------------------------------------- > #!/usr/bin/python > import numpy > file = open('matrix.txt', 'r') > > count = 0 > ra = numpy.random > A = ra.standard_normal((4,4)) > while 1: > lineStr = file.readline() > if not(lineStr): > break > > count = count + 1 > row=split(lineStr) > A[count,:]=row > > matrix.close() > ----------------------------------------------------- > Also, i want to initialize the matrix A by zeros, but using A=zeros([4, > 4]) was giving a similar error "NameError: name 'zeros' is not > defined". > > Thank you > Amit This is how I would do it. for lineStr in file: ...row = lineStr.split() you could also use str.split(lineStr) but the other way is cleaner From rajani.vemula at gmail.com Thu Nov 9 07:06:53 2006 From: rajani.vemula at gmail.com (Raj) Date: 9 Nov 2006 04:06:53 -0800 Subject: Post data using the libcurl Message-ID: <1163074013.616584.281450@b28g2000cwb.googlegroups.com> Hi, I am newbie to programming with libcurl. the problem is i want to send my gmail username and password outside the browser and get access to my mail. this i am doing with LibCurl. Though i dont get any errors, i am nt able to get the o/p Can anyone kindly help. i will attach the program here #include #include #include int main(int argc, char *argv[]) { CURL *curl; CURLcode res; struct curl_httppost *formpost=NULL; struct curl_httppost *lastptr=NULL; struct curl_slist *headerlist=NULL; char buf[] = "Expect:"; curl_global_init(CURL_GLOBAL_ALL); /* Fill in the file upload field */ curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "rajani.vemula", CURLFORM_END); /* Fill in the filename field */ curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "xxxxx", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "null", CURLFORM_COPYCONTENTS, "Sign in", CURLFORM_END); curl = curl_easy_init(); /* initalize custom header list (stating that Expect: 100-continue is not wanted */ headerlist = curl_slist_append(headerlist, buf); if(curl) { /* what URL that receives this POST */ curl_easy_setopt(curl, CURLOPT_URL," http://mail.google.com/mail"); curl_easy_setopt(curl, CURLOPT_PROXY, "proxyname"); curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, "User:Password)"; /* only disable 100-continue header if explicitly requested */ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); res = curl_easy_perform(curl); /* always cleanup */ curl_easy_cleanup(curl); /* then cleanup the formpost chain */ curl_formfree(formpost); curl_slist_free_all(headerlist } return 0; } Thanks From junk.rubbish at alma-services.abel.co.uk Sat Nov 11 17:46:38 2006 From: junk.rubbish at alma-services.abel.co.uk (Sandy) Date: Sat, 11 Nov 2006 22:46:38 +0000 Subject: Python Parallel Paradigm References: <1163272625.991469.153870@i42g2000cwa.googlegroups.com> <4556246a$0$326$e4fe514c@news.xs4all.nl> <1163276885.609160.163090@h54g2000cwb.googlegroups.com> Message-ID: In article <1163276885.609160.163090 at h54g2000cwb.googlegroups.com>, Mythmon at gmail.com wrote >Well, I tried that, and it did something. It made it so the space bar >switched the clock once, but not a second time. And it still crashed, >but not always at the same time, sometimes it would do it the second >time I hit the space bar, sometimes before I hit it the first time, but >always when i did something that would generate a Console event (moving >the mouse or something). So, I thought it had something to do with >Console not working well with threads, so I took it completely out of >threads and had just the event checking loop run by itself, and it >still crashed. So apparently I am using the Console events wrong. I am >going to try and find some examples online on how to watch for events >with it, but if worse comes to worse I can try and use keyboard hooks, >I've looked at those before, and they might work better. Dear Pythonauts, I usually lurk on the comp.lang.python newsgroup. I'm not an expert in the slightest, but I have had a growing feeling that there's something definitely lacking in the concurrency aspects of Python. It is the same problem with Java. Forgive me if I don't know the right vocabulary, but Python concurrency seems to be exposed at too "low a level". It's like assembler: it's all _possible_ to implement, but in practise it's very complicated and fragile, glitchy, and really difficult to extend. Like programming in Dartmouth BASIC with just conditionals and "goto" instructions, before structured programming. A higher-level system of concurrency, not based on monitors and locks and great programmer discipline, will ultimately require making "Python 3000" a reality. In the meantime, is there anywhere, or any thing, that discusses the various concurrency options related to Python? There's Stackless Python (which I can't make head or tail of; I have been unable to find any lucid overview, or genuine explanation of the purpose of the design.) I know that there's a package for an Erlang system for Python, somewhere ("Parnassus" probably). There's probably a Py-CSP somewhere too. Lots of trees, but where's the Wood? Where are concurrency/distributed models compared and discussed? With kind regards, Sandy -- Alexander Anderson (Yorkshire, England) Where there is no vision, the people perish. From CRhode at LacusVeris.com Wed Nov 29 21:45:09 2006 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Wed, 29 Nov 2006 20:45:09 -0600 Subject: PythonTidy Message-ID: <20061130024509.GA8961@loki> I couldn't find a routine to clean up, regularize, and reformat Python code, so I wrote one: http://www.lacusveris.com/PythonTidy/PythonTidy.python Now, I'm looking for beta-testers. Compensation is a bit on the low side. In fact it's limited to the satisfaction of helping out. Thanks. -- .. Chuck Rhode, Sheboygan, WI, USA From nitte.sudhir at gmail.com Mon Nov 13 13:37:32 2006 From: nitte.sudhir at gmail.com (kath) Date: 13 Nov 2006 10:37:32 -0800 Subject: A question on Encoding and Decoding. Message-ID: <1163443052.228761.318200@h54g2000cwb.googlegroups.com> Hi all, Platform: winxp Version: Python 2.3 I have a task of reading files in a folder and creating an one excel file with sheets, one sheet per file, with sheet named as filename. I am facing problem in handling special characters. I am using XLRD and XLW package to read/write from/to file. But facing problem in handling special characters. I am getting encode error. UnicodeDecodeError 'ascii' codec can't encode character u'\xdf' in position 19: ordinal not in range(128) row: 76 the cell value at rowx = 76, colx = 0 is 'Activest-Aktien-Gro?britannien' I used Latin-1 encoding, but after the file is created I get an error 'Unable to read the file'. When I get the exception I want to format the string so that I can use it to write to a file and also query database. Can anybody guide how to solve this problem. what encoding I should use, and after wring to file I should the same special character. Also python IDLE is able to output the same character corretly when I say print and why not I? Any suggestions would be greatly appreciated. thanks. regards, kath. From ronrsr at gmail.com Fri Nov 10 12:27:02 2006 From: ronrsr at gmail.com (ronrsr) Date: 10 Nov 2006 09:27:02 -0800 Subject: SyntaxError: Invalid Syntax. In-Reply-To: References: <1163178099.156160.29280@k70g2000cwa.googlegroups.com> <1163178336.281812.140580@f16g2000cwb.googlegroups.com> <1163178581.231837.18120@h48g2000cwc.googlegroups.com> Message-ID: <1163179622.691812.96170@h48g2000cwc.googlegroups.com> the exact code that is triggering the error message is: zc = zsql.connect() exact error message: SyntaxError: Invalid Syntax but any statement that follows the import statement will trigger it. bests, r-sr- Roberto Bonvallet wrote: > ronrsr wrote: > > thanks for the speedy answer. what i meant was: > > > Could you please copy and paste the exact code that is triggering the > error, and the exact error message? > > (BTW, in Python you don't need to end your statements with a semi-colon) > -- > Roberto Bonvallet From ardsrk at gmail.com Sat Nov 4 07:31:29 2006 From: ardsrk at gmail.com (ArdPy) Date: 4 Nov 2006 04:31:29 -0800 Subject: small python cgi webserver In-Reply-To: References: <1162635479.491109.15640@h54g2000cwb.googlegroups.com> Message-ID: <1162643489.722245.262290@m7g2000cwm.googlegroups.com> Fabian Braennstroem wrote: > Hi, > > * ArdPy wrote: > > > > Fabian Braennstroem wrote: > >> Hi, > >> > >> I am looking for a small python script, which starts a small > >> web server with python cgi support on a linux machine. > >> > >> I tried: > >> > >> > >> #!/usr/bin/env python > >> import sys > >> from CGIHTTPServer import CGIHTTPRequestHandler > >> import BaseHTTPServer > >> > >> class MyRequestHandler(CGIHTTPRequestHandler): > >> # In diesem Verzeichnis sollten die CGI-Programme stehen: > >> cgi_directories=["/home/fab/Desktop/cgi-bin"] > >> > >> > >> def run(): > >> # 8000=Port-Nummer > >> # --> http://localhost:8000/ > >> # Fuer http://localhost/ > >> # Port-Nummer auf 80 setzen > >> httpd=BaseHTTPServer.HTTPServer(('', 8000), MyRequestHandler) > >> httpd.serve_forever() > >> > >> if __name__=="__main__": > >> print "Starting Server" > >> run() > >> > >> but when I want to test a small python cgi test file: > >> > >> > >> #!/usr/bin/python > >> # -*- coding: UTF-8 -*- > >> > >> # Debugging f?r CGI-Skripte 'einschalten' > >> import cgitb; cgitb.enable() > >> > >> print "Content-Type: text/html;charset=utf-8\n" > >> print "Hello World!" > >> > >> I just get the text and not the html output. The file's mode > >> is 755. > >> > >> Is there anything wrong with the webserver script or do I do > >> something completely wrong? Maybe, you have a different > >> webserver script? > >> > >> Greetings! > >> Fabian > > > > Probably the server is not executing your CGI script. If it is the > > Apache web server that you are using then just ensure the following > > settings in your /etc/httpd/conf/httpd.conf file is exactly like > > following: > > > > > > AllowOverride None > > Options ExecCGI > > Order allow,deny > > Allow from all > > > > Maybe, I understood something wrong, but I thought that the > above 'webserver' script would replace apache in my case; at > least I hoped!? > > Greetings! > Fabian Oh yes...Your script is supposed to replace apache. I tried with your script on my pc and its working just fine. However the problem still is that the server is taking your file to be a plain file rather than a CGI script. Looking at CGIHTTPServer.is_cgi method might prove helpful. From fredrik at pythonware.com Thu Nov 16 03:11:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 09:11:58 +0100 Subject: How to make a python file to a DLL? In-Reply-To: <1163663993.261179.146630@m7g2000cwm.googlegroups.com> References: <1163663993.261179.146630@m7g2000cwm.googlegroups.com> Message-ID: many_years_after wrote: > Any solution? python modules are usually shipped in ZIP archives, not DLLs. if you really need a DLL, you can use "freeze" and some custom hacking. or bytecode resources, and some more custom hacking. From insyte at gmail.com Tue Nov 14 11:39:13 2006 From: insyte at gmail.com (insyte at gmail.com) Date: 14 Nov 2006 08:39:13 -0800 Subject: __cmp__ between dissimilar objects In-Reply-To: References: <1163464397.679361.215050@m7g2000cwm.googlegroups.com> Message-ID: <1163522353.529662.58050@f16g2000cwb.googlegroups.com> > why not just inherit from datetime instead? I'll probably do that in the next iteration. > or read footnote 4 under "supported operations" on this page for info on how to > implement mixed-type comparisions: > > http://docs.python.org/lib/datetime-datetime.html OK. I added a 'timetuple' attribute to my class. Now comparisons seem to "just work". This has made it even more obvious to me that I don't understand how comparisons function: If the GeneralizedTime instance is on the LHS of the comparison and the datetime instance on the RHS, why would datetime's __cmp__ method be called? I assume its being called since GeneralizedTime sure doesn't care whether or not it has a timetuple attribute... I've read through the "Basic customization" section of the language reference, which doesn't seem to describe a scenario where the __cmp__ method on the RHS is called. Thanks... -Ben From guy.flowers at Machineworks.com Thu Nov 23 09:19:35 2006 From: guy.flowers at Machineworks.com (guy.flowers at Machineworks.com) Date: 23 Nov 2006 06:19:35 -0800 Subject: non blocking "i o", The deep freeze. Message-ID: <1164291575.215166.29330@m7g2000cwm.googlegroups.com> Hi Have a problem, Ill give some history to the problem and add a little example code to start with to see if anybody can help or if I am correct in what the problem is. I have been looking on the newsgroups and have found lots of stuff on the problem but no solutions as of yet, will keep looking here to see if I can find one that fits. I created a script which runs a whole suite of regression tests, the test exe which is built daily, is created from c code, this changes from day to day as stuff is added, and fixed, the exe is then used to run text files which have lots of commands and data in, which produce lots of pretty pictures on the screen, errors and warning output is also produced from this, which I collect and create logs with. Up until recently I havn't had any problems with my script, the main tests were run on a local win32 machine with all the logs and test files all local, with occasional runs on various different unix's and win64 platforms. We have just recently had installed a big test and build rack full of win32 (winxp) machines 3 of these are automated test machines which run my script in a loop (it also builds the test exe and does one or two other things), the test files are now held on a big central disk, which was ment to save me coping data down from the network. The whole thing works pretty well, a part from every so offen completely randomly the 3 machines seem to freeze (or to put in the terms of our sys admin it trashes them). The machines needs to be reset and the connection between the machines and the big central disk is lost and needs to be reset as well. According to the sys admin I need to be using, non blocking "i o" for my file control, the code below shows what Im doing at the moment. Has any one got any suggestions on what to do here, I kept everything really simple so it would work across all platform and I thought I was there, but like with most things, its not and the code will probably get really complex. The code below is only a small snipet and I've made it simple for this example but its the part I think where the freeze is happening. output, input = popen2("cmd.exe") input.write("set LI_DIR=" + MW_OPTS.GetOption("MainOpts","LI_DIR") + "\n") input.write("set LI\n") # Writes commands to it. input.write(mwtest_exe + mwtest_args + os.path.dirname(f_testlwc_str) + testlwc + "\n") input.write("exit\n") while 1: text = output.readline() if text: OutputCount += 1 # Searches the line for errors, when found stops doing this. f_Error_Code = FileLineQuickStat(text , f_Possible_Errs_dict , f_Error_Code) # Records the line in a log. LW_FLOG.WriteLogEntry("TEST_LOG",str(OutputCount),string.replace(text,"\n",""),1) else: LW_FLOG.FinishLog("TEST_LOG","") # Returns the error code. return f_Error_Code break TIA Guy From steve at REMOVE.THIS.cybersource.com.au Sat Nov 11 01:25:39 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 11 Nov 2006 17:25:39 +1100 Subject: mushrooms are animals? [was Re: Py3K idea: why not drop the colon?] References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> Message-ID: On Fri, 10 Nov 2006 22:41:53 -0600, skip wrote: > > Steven> The world seems to be flat, the sun appears to rotate around the > Steven> Earth, and mushrooms look like they are more closely related to > Steven> plants than to animals, but none of these things are actually > Steven> the case. > > Where can I read about mushrooms as animals? Mushrooms, like all fungi, aren't animals. The old divide of the living world into animals and plants has been obsolete in biology for decades. Biologists today generally follow Woese's "Six Kingdoms": Eubacteria ("ordinary bacteria") Archaebacteria ("extrophile bacteria") Fungi Plantae (plants) Animalia (animals) Protista (eukaryotes that are neither fungi, plants or animals -- a grab-bag of "things left over" such as protozoa and algae) Notice that, although to the naked microscope eubacteria and archaebacteria seem very similar, their biochemistry is radically different -- more so than (say) an oak tree and you or I. Based on molecular and DNA evidence, fungi and animals are more similar than fungi and plants. (Remember that animals include many thousands of species that don't walk or crawl or fly, beasties like corals, sponges and other creatures that look superficially plant-like.) Both animals and fungi rely on plants to convert solar energy into chemical forms that they can digest. The best evidence is that the animal kingdom (including, naturally, human beings) and fungi split during the Mesoproterozoic Era, approximately 1500-2000 million years ago. The common ancestor ("concestor") of animals and fungi split from plants not long before that, where by "not long" I of course mean "many hundreds of millions of years". Richard Dawkins' excellent book "The Ancestor's Tale" is worth reading for more about this. But keep in mind that biology is in a constant state of flux these days, with new molecular discoveries virtually every day, so dates are naturally uncertain and subject to revision. (Aside: this willingness, even desire, to revise old beliefs in the light of new evidence disproves the Creationist canard that evolution is a matter of faith rather than science -- but I digress.) See also http://en.wikipedia.org/wiki/Fungi for more about fungi including mushrooms, although regrettably little on their evolutionary relationship with other species. Follow the references there to discover more. http://en.wikipedia.org/wiki/Kingdom_%28biology%29 discusses the biological kingdoms -- again, treat Wikipedia as the start, not the end, of your reading :) -- Steven. From cyberco at gmail.com Wed Nov 22 03:09:40 2006 From: cyberco at gmail.com (cyberco) Date: 22 Nov 2006 00:09:40 -0800 Subject: Is python for me? In-Reply-To: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> References: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> Message-ID: <1164182979.958434.243130@k70g2000cwa.googlegroups.com> One resource you should always keep at hand is this extremely useful Quick Reference: http://rgruet.free.fr/PQR24/PQR2.4.html Study it carefully, there is a lot in there that can teach you about how Python works. Fire up IPython as well and start hacking! 2B From tom at t0mb.net Sat Nov 18 12:22:02 2006 From: tom at t0mb.net (tom) Date: Sat, 18 Nov 2006 17:22:02 +0000 Subject: basic python questions In-Reply-To: <455F3F24.2080609@t0mb.net> References: <1163829271.660193.70450@j44g2000cwa.googlegroups.com> <1163868656.416276.277310@m7g2000cwm.googlegroups.com> <455F3F24.2080609@t0mb.net> Message-ID: <455F413A.5010409@t0mb.net> tom wrote: > nateastle at gmail.com wrote: > >> I have taken the coments and think I have implemented most. My only >> question is how to use the enumerator. Here is what I did, I have tried >> a couple of things but was unable to figure out how to get the line >> number. >> >> >> > Try this in the interpreter, > > l = [5,4,3,2,1] > for count, i in enumerate(l): > print count, i > > > you could do it like this. for count, line in enumerate(fb): for word in line.split(): etc... filehandles are iterators themselves. dont take my words for granted though, i'm kinda new to all this too :) >> def Xref(filename): >> try: >> fp = open(filename, "r") >> except: >> raise "Couldn't read input file \"%s\"" % filename >> dict = {} >> line_num=0 >> for words in iter(fp.readline,""): >> words = set(words.split()) >> line_num = line_num+1 >> for word in words: >> word = word.strip(".,!?:;") >> if not dict.has_key(word): >> dict[word] = [] >> dict[word].append(line_num) >> fp.close() >> keys = sorted(dict); >> for key in keys: >> print key," : ", dict[key] >> return dict >> >> Marc 'BlackJack' Rintsch wrote: >> >> >>> In <1163829271.660193.70450 at j44g2000cwa.googlegroups.com>, >>> nateastle at gmail.com wrote: >>> >>> >>> >>>> def Xref(filename): >>>> try: >>>> fp = open(filename, "r") >>>> lines = fp.readlines() >>>> fp.close() >>>> except: >>>> raise "Couldn't read input file \"%s\"" % filename >>>> dict = {} >>>> for line_num in xrange(len(lines)): >>>> >>>> >>> Instead of reading the file completely into a list you can iterate over >>> the (open) file object and the `enumerate()` function can be used to get >>> an index number for each line. >>> >>> >>> >>>> if lines[line_num] == "": continue >>>> >>>> >>> Take a look at the lines you've read and you'll see why the ``continue`` >>> is never executed. >>> >>> >>> >>>> words = lines[line_num].split() >>>> for word in words: >>>> if not dict.has_key(word): >>>> dict[word] = [] >>>> if line_num+1 not in dict[word]: >>>> dict[word].append(line_num+1) >>>> >>>> >>> Instead of dealing with words that appear more than once in a line you may >>> use a `set()` to remove duplicates before entering the loop. >>> >>> Ciao, >>> Marc 'BlackJack' Rintsch >>> >>> >> >> > > From martin at v.loewis.de Sat Nov 4 12:26:13 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 04 Nov 2006 18:26:13 +0100 Subject: win32file.DeviceIoControl(FSCTL_GET_RETRIEVAL_POINTERS) In-Reply-To: <1162660691.829676.85990@h48g2000cwc.googlegroups.com> References: <1162660691.829676.85990@h48g2000cwc.googlegroups.com> Message-ID: <454CCD35.6010201@v.loewis.de> Jim schrieb: > I'm not sure how to perform this operation in Python. The difficulty is > in knowing the size of the output buffer: if it is too small, I get an > "insufficient buffer" exception; too large, and I get an "end of file" > exception. In neither case is any partial data available. What precisely is the "end of file" exception you are getting. Looking at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/fsctl_get_retrieval_pointers.asp I'd say it is ERROR_HANDLE_EOF The volume is an NTFS file system volume and the requested starting VCN is past the end of the file. So my guess is you should just pass a smaller starting VCN. Regards, Martin From grante at visi.com Sat Nov 25 09:22:30 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 25 Nov 2006 14:22:30 -0000 Subject: Simple threading References: <1164295697.757788.26710@e3g2000cwe.googlegroups.com> Message-ID: <12mgkd6e5cp5l16@corp.supernews.com> On 2006-11-25, Gabriel Genellina wrote: >>I'm just getting started on threading and was wondering why the >>following code does not work (i know globals is bad style - I'll >>eliminate them eventually). All I get is a blank cursor flashing. > > You've got your example already working. Globals are bad > style, but worse, threads and globals don't mix very well: you > need some sort of syncronization for accessing globals > (specially for writing them). That depends on the type of the global and how they're used. Re-binding a name is always an atomic operation. Modifying many mutable objects is atomic. >>class ImapThread(threading.Thread): >> def run(self): >> global g_currenttick >> if time.time() > (g_datum + (g_secondspertick * >>g_currenttick)): >> print "Ticked %s" % g_currenttick >> g_currenttick=g_currenttick+1 >> print g_currenttick > > Having more than one thread, g_currenttick could have been modified > *after* you read its value and *before* you write it back, so you > lose the count. Right. Reading an integer object in one statement and writing it in a subsequent statement is not an atomic opteration unless protected by some synchronization mechanism. -- Grant Edwards grante at visi.com From fredrik at pythonware.com Sat Nov 25 10:47:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 25 Nov 2006 16:47:45 +0100 Subject: Dynamic function execution In-Reply-To: <1164469406.980376.194150@h54g2000cwb.googlegroups.com> References: <1164469406.980376.194150@h54g2000cwb.googlegroups.com> Message-ID: Andy Wu wrote: > def func(seconds = None, minutes = None, hours = None): > ... > > In my program I can get a string object('seconds', 'minutes', 'hours') > to specify which parameter to use, the problem is I don't know how to > call the function. > > Say I have a string 'minutes' and a integer 30, now I need to call the > func this way: func(minutes = 30), how do I do this? func(**{"minutes": 30}) From tejovathi.p at gmail.com Thu Nov 2 00:52:30 2006 From: tejovathi.p at gmail.com (Teja) Date: 1 Nov 2006 21:52:30 -0800 Subject: Regular Expression for a string In-Reply-To: <1162445312.608506.177340@m7g2000cwm.googlegroups.com> References: <1162440285.962155.325540@f16g2000cwb.googlegroups.com> <1162445312.608506.177340@m7g2000cwm.googlegroups.com> Message-ID: <1162446750.170597.84480@b28g2000cwb.googlegroups.com> John Machin wrote: > Teja wrote: > > HI all, > > > > I need to write a regular experssion for a string which satisfies the > > following a criteria : > > > > 1) it should start with an alphabet > > 2) it can contain alphabets/digits/_ from second character > > 3) it can contain "[a-z]" or "[0-9]" at the end. but this is optional > > Based on the examples you give later, you don't mean "optional" (0 or 1 > occurrences), you mean 0 or more occurrences. > Assuming "alphabet" means "English alphabetic": > > r"[a-zA-Z][a-zA-Z0-9_]*(\[[a-z0-9]\])*" > > HTH, > John Thnks a lot....:) From bernard.chhun at gmail.com Thu Nov 9 07:48:31 2006 From: bernard.chhun at gmail.com (Bernard) Date: 9 Nov 2006 04:48:31 -0800 Subject: substring search without using built in utils In-Reply-To: References: Message-ID: <1163076511.535543.231190@e3g2000cwe.googlegroups.com> do your homework and use regexes! but the find() and in() function works great for normal strings...why don't you want to use them? zeal elite a ?crit : > Hi, > > I am looking for substring search python program without using the built in > funtions like find, or 'in'. > > Appreciate it. Thanks in advance. > zeal > > _________________________________________________________________ > Find a local pizza place, music store, museum and more...then map the best > route! http://local.live.com?FORM=MGA001 From tundra at tundraware.com Wed Nov 8 15:59:38 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: Wed, 08 Nov 2006 14:59:38 -0600 Subject: Problem getting a file pathname with tkFileDialog In-Reply-To: <1163016063.961485.224390@k70g2000cwa.googlegroups.com> References: <1163012468.055428.124690@h48g2000cwc.googlegroups.com> <1163016063.961485.224390@k70g2000cwa.googlegroups.com> Message-ID: Sefyroth wrote: > Thanks, > > but I get this error when I try this. > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in > position 12: ordinal not in range(128) > > I had encountered it with the askdirectory method as well. Is there an > easy way to bypass this? > > Thanks again I believe you are running into a directory or file name that has non-ascii characters in it. Python as shipped is set up to deal with ascii as its native encoding format. You can change this by editing the "site.py" file - look in the Lib directory in your python installation. Look for this code: ------------------------------- def setencoding(): """Set the string encoding used by the Unicode implementation. The default is 'ascii', but if you're willing to experiment, you can change this.""" encoding = "ascii" # Default value set by _PyUnicode_Init() if 0: # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] ------------------------------- Change the "if 0:" to "if 1:" and see if that doesn't fix the problem. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From steven.bethard at gmail.com Mon Nov 6 10:56:13 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 06 Nov 2006 08:56:13 -0700 Subject: Python Distilled In-Reply-To: <1162790565.418382.237050@m73g2000cwd.googlegroups.com> References: <1162790565.418382.237050@m73g2000cwd.googlegroups.com> Message-ID: <08Odnc6j7uKLxtLYnZ2dnUVZ_oydnZ2d@comcast.com> Simon Wittber wrote: > I want to build a Python2.5 interpreter for an embedded system. I only > have 4MB of RAM to play with, so I want to really minimise the python > binary. [snip] > Google tells me that people have done this before, back in Python1.5.2 > days. Has anyone tried to do this recently with a more modern Python? http://www.python.org/dev/summary/2006-09-16_2006-09-30/#shrinking-python STeVe From nospam at domain.tld Sat Nov 25 03:52:42 2006 From: nospam at domain.tld (Stephan Kuhagen) Date: Sat, 25 Nov 2006 09:52:42 +0100 Subject: Ruby/Python/REXX as a MUCK scripting language References: <2006112418112116807-zobeid@techiecom> Message-ID: Tony Belding wrote: > Is this practical? I'm thinking of Ruby or Python for this, if they > can meet the requirements. Python had a sandbox module, but is was discarded because of security problems. If you want it working on MacOS, you may also have a look at Tcl, which has a long tradition on MacOS and it comes with a very good implemented and fully customizable sandbox. For a starting point, if Tcl sandbox meets your requirements, have a look here: Safe Tcl Overview: http://www.tcl.tk/software/plugin/safetcl.html Docs about the specific Tcl commands, to create safe interpreters: http://www.tcl.tk/man/tcl8.4/TclCmd/interp.htm (See in the lower third of the page at "Safe Interpreters") http://www.tcl.tk/man/tcl8.4/TclCmd/safe.htm Regards Stephan From jorge.vargas at gmail.com Mon Nov 6 01:07:46 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 6 Nov 2006 06:07:46 +0000 Subject: how to write code into a blog post? In-Reply-To: <1162680019.930647.36130@m7g2000cwm.googlegroups.com> References: <1162680019.930647.36130@m7g2000cwm.googlegroups.com> Message-ID: <32822fe60611052207r704ba1f9ndd4d5ef281cf37c6@mail.gmail.com> On 4 Nov 2006 14:40:19 -0800, thebjorn wrote: > Jorge Vargas wrote: > > Hi I know many people here blog so sorry for the OT. > > > > Currently I have a wordpress install and went I wanted to post some > > code I notice how painfull it is. > > Indeed :-) I'm using the iG:Syntax Hiliter over on > http://blog.tkbe.org after I got some comments about the lack of > readability of my code samples ;-) It can be even more colorful than > I've set it up, but it handles a considerable number of languages and > is pretty simple to both use and manage. You can get it at: > http://blog.igeek.info/wp-plugins/igsyntax-hiliter/ I added the > following to the end of the stylesheet to make the code frame bigger > and dynamic: > > div.igBar { width: 95%; } > div.syntax_hilite { width:95%; } > thanks I'll take a look at it > hth, > -- bjorn > > -- > http://mail.python.org/mailman/listinfo/python-list > From paul at boddie.org.uk Tue Nov 7 05:32:34 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 7 Nov 2006 02:32:34 -0800 Subject: Pyro stability References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <454dd84b$0$328$e4fe514c@news.xs4all.nl> <1162783631.291535.221530@f16g2000cwb.googlegroups.com> <454fdbc5$0$335$e4fe514c@news.xs4all.nl> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> Message-ID: <1162895554.549926.49280@k70g2000cwa.googlegroups.com> Beliavsky wrote: > Carl J. Van Arsdall wrote: [Enthusiasm for Pyro, not for those with sensitivity to rude words] > You should watch your language in a forum with thousands of readers. It was quite an endorsement, though. ;-) Paul From wileyregister22 at gmail.com Tue Nov 28 03:55:34 2006 From: wileyregister22 at gmail.com (wileyregister22 at gmail.com) Date: 28 Nov 2006 00:55:34 -0800 Subject: Accessing file metadata on windows XP Message-ID: <1164704134.100569.101270@j72g2000cwa.googlegroups.com> When rightclicking a, for example, pdf file on windows, one normally gets a screen with three or four tags. Clicking on one of the summary tag one can get some info like "title", "Author", "category", "keyword" etc.. My question is how can I programmatically read and change these data with python. I know I should use Hammond's win32 extension, somehow involving the pythoncom, storagecon of win32com etc.. Unfortunately, so far I cannot get anything useful. Instead of trying blindly, would somebody please points me to the correct direction. A little snippet would help. I am particular interested in pdf files. From python at hope.cz Thu Nov 9 04:52:49 2006 From: python at hope.cz (Lad) Date: 9 Nov 2006 01:52:49 -0800 Subject: Sorted list - how to change it Message-ID: <1163065969.593970.165600@b28g2000cwb.googlegroups.com> I have a sorted list for example [1,2,3,4,5] and I would like to change it in a random way e.g [2,5,3,1,4] or [3,4,1,5,2] or in any other way except being ordered. What is the best/easiest way how to do it? Thank you for help L. From mike.klaas at gmail.com Wed Nov 8 01:21:41 2006 From: mike.klaas at gmail.com (Klaas) Date: 7 Nov 2006 22:21:41 -0800 Subject: Python memory usage In-Reply-To: <1162964551.328495.211090@f16g2000cwb.googlegroups.com> References: <1162964551.328495.211090@f16g2000cwb.googlegroups.com> Message-ID: <1162966901.337252.45720@m7g2000cwm.googlegroups.com> placid wrote: > Hi All, > > Just wondering when i run the following code; > > for i in range(1000000): > print i > > the memory usage of Python spikes and when the range(..) block finishes > execution the memory usage does not drop down. Is there a way of > freeing this memory that range(..) allocated? Python maintains a freelist for integers which is never freed (I don't believe this has changed in 2.5). Normally this isn't an issue since the number of distinct integers in simultaneous use is small (assuming you aren't executing the above snippet). -Mike From steve at holdenweb.com Sat Nov 11 13:31:19 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 11 Nov 2006 12:31:19 -0600 Subject: Assistance needed with PyCon sponsorship system Message-ID: It's that time of year again and the Python Software Foundation is cranking up for the fifth PyCon, again this year in Texas. I am responsible for bringing in the sponsorship funds that help to keep this event so reasonably priced, and last year I built a PostgreSQL database to help with the emailing and the invoicing. However it needs some work, which I may not have time to complete myself, to make it easier to use and to improve reporting. Naturally the software, such as it is, is written entirely in Python. Is there anyone out there who'd be prepared to help me with this project? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Thu Nov 2 01:30:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 02 Nov 2006 07:30:23 +0100 Subject: need to find out all modules from site-packages In-Reply-To: References: Message-ID: alf wrote: > I need to find all modules/lib from the site-packages along with the > versions. Is there a way to determine physical path to the module? > > And is there is a way to identify all potential "importable" modules? maybe this could be a start? http://online.effbot.org/2006_10_01_archive.htm#listmodules-cgi http://svn.effbot.python-hosting.com/stuff/sandbox/cgi/listmodules.cgi (this works as a local script too) From icebergwtf at yahoo.com.cn Fri Nov 3 01:03:40 2006 From: icebergwtf at yahoo.com.cn (Tiefeng Wu) Date: Fri, 3 Nov 2006 14:03:40 +0800 (CST) Subject: Make all files extension lower by a given directory name Message-ID: <20061103060340.1559.qmail@web15011.mail.cnb.yahoo.com> Tim Chase wrote: > Having a win32 program take case-sensitive filenames is a bit > odd, given that the OS is case-agnostic...however, that doesn't > preclude bad programming on the part of your tool-maker. Alas. > > Thus, to accomodate the lousy programming of your tool's maker, I > proffer this: > > I've found that Win32 doesn't often take a rename if the origin > and destination differ only in case[*]. Thus, to change the > case, I've had to do *two* renames...one to, say, prefix with an > underscore and change the case to my desired case, and then one > to strip off the leading underscore. You might try a similar > song-and-dance to strong-arm Windows into specifying the case of > the file. Something like this (untested) code: > > filename = "Spanish Inquisition.TGA" > name, ext = splitext(filename) > intermediate = "_" + name + ext.lower() > rename(filename, intermediate) > rename(intermediate, intermediate[1:]) > > And then I'd wrap this contrived abomination in plenty of > comments so that folks coming back to it understand why you're > using three lines to do what "should" be just > > rename(filename, name + ext.lower()) > > as would be the "right" way to rename the file with a lowercase > version of its extension. > > Yes, it's an odd filename choice there which you might not have > expected...nobody expects the Spanish Inquisition... > > -tkc > > [*] Have had problems with this both in Explorer and at the > command prompt. Yes, that's tool maker's fault. I think he used string compare in his code with case-sensitive (coded in c#, btw). I started study python about a month, so I hope my problem not bother you :) Anyway, I realize python is an amazing language and a power tool, thank you. wutiefeng 2006-11-03 ___________________________________________________________ ??????-3.5G???20M?? http://cn.mail.yahoo.com/ From Leo.Kislov at gmail.com Tue Nov 21 04:41:45 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 21 Nov 2006 01:41:45 -0800 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? References: <18c54$455d019b$59ad1aca$24364@news.flashnewsgroups.com> <455d507d$0$18480$9b622d9e@news.freenet.de> <3188c$455d923f$59ad1aca$4742@news.flashnewsgroups.com> <455E5D15.7030207@v.loewis.de> <3e540$4560b958$59ad1aca$32456@news.flashnewsgroups.com> <4560E3AE.5030307@v.loewis.de> <1163992410.229236.60830@e3g2000cwe.googlegroups.com> <4561515B.4060106@v.loewis.de> <1164046257.736569.267090@j44g2000cwa.googlegroups.com> <45623696.90504@v.loewis.de> Message-ID: <1164102105.330879.137300@b28g2000cwb.googlegroups.com> Martin v. L?wis wrote: > Ross Ridge schrieb: > > Ross Ridge schrieb: > >> That would conflict with private use characters appearing in file > >> names. > > > > Martin v. L?wis wrote: > >> Not necessarily: they could get escaped. > > > > How? > > Suppose I use U+E001..U+E0FF as the PUA characters for unencodable > bytes; U+E000 wouldn't be needed since it \0 cannot be part of > a file name in POSIX. > > Then I would use U+E000 for escaping. Each PUA character in the > listed file name would get escaped with U+E000 in the Python > string; when the file name is converted back to the system, it > gets unescaped. > > Notice that I think this is a really unrealistic case - I expect > that all file names containing PUA characters were deliberately > crafted to investigate using PUA characters in file names. How will it interoperate with non-python world? Will these file names ever escape python process? Unicode consortium thinks "safe" utf-8 is a bad idea: http://www.mail-archive.com/unicode at unicode.org/msg27241.html [Lars Kristan] > Which could be understood as "a proposal to amend UTF-8 to allow invalid > sequences". [Kenneth Whistler, Technical Director, The Unicode Consortium] O.k., and as pointed out already, that simply won't fly. *Nobody* in the UTC or WG2 is going to go for that. It would destroy UTF-8, not fix it. --------------------------------- Kenneth Whistler on invalid file names: http://www.mail-archive.com/unicode at unicode.org/msg27225.html And also: http://www.mail-archive.com/unicode at unicode.org/msg27167.html [Lars Kristan] > Should all > filenames that do not conform to UTF-8 be declared invalid? [Doug Ewell, the guy behind Unicode Technical Note #14] If you have a UTF-8 file system, yes. -------------------------------------------------------------- -- Leo From writetosrj at gmail.com Thu Nov 9 02:38:17 2006 From: writetosrj at gmail.com (srj) Date: 8 Nov 2006 23:38:17 -0800 Subject: which is a good imaging lib in python?? Message-ID: <1163057897.010765.46780@h48g2000cwc.googlegroups.com> hi can any1 tell me which is a good imaging lib in python and where i can get it (2 dwnld) from?? regds From fredrik at pythonware.com Sat Nov 11 19:25:53 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Nov 2006 01:25:53 +0100 Subject: reduce to be removed? In-Reply-To: <1163290526.013063.245130@m7g2000cwm.googlegroups.com> References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163288885.884417.218270@f16g2000cwb.googlegroups.com> <1163290526.013063.245130@m7g2000cwm.googlegroups.com> Message-ID: Dustan wrote: >> > Because I'm embedding this expression in a list comprehension >> >> because? > > Because I thought I would be able to get an answer without revealing > the exact details of what I am doing. alright, let's try again: why do you need a self-contained reduce replacement that can be embedded inside a list comprehension ? From webmaster at cacradicalgrace.org Mon Nov 20 14:32:16 2006 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Mon, 20 Nov 2006 12:32:16 -0700 Subject: remove a list from a list References: Message-ID: Rares Vernica wrote: > Hi, > > I have the following problem: > > I have a list like > e = ['a', 'b', 'e'] > and another list like > l = ['A', 'a', 'c', 'D', 'E'] > I would like to remove from l all the elements that appear in e > case-insensitive. That is, the result would be > r = ['c', 'D'] > > What is a *nice* way of doing it? > > Thanks a lot, > Ray > if you can guarantee that e will always be made up of lowercase letters, then you can do the following: r = [ x for x in l if x.lower() not in e ] Cheers, Cliff From paul at boddie.org.uk Sun Nov 12 09:45:01 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 12 Nov 2006 06:45:01 -0800 Subject: Python Parallel Paradigm References: <1163272625.991469.153870@i42g2000cwa.googlegroups.com> <4556246a$0$326$e4fe514c@news.xs4all.nl> <1163276885.609160.163090@h54g2000cwb.googlegroups.com> Message-ID: <1163342701.819347.203110@i42g2000cwa.googlegroups.com> Sandy wrote: > > A higher-level system of concurrency, not based on monitors and > locks and great programmer discipline, will ultimately require making > "Python 3000" a reality. It would surprise me if Python 3000 introduced anything substantially more than what Python 2.x provides in the area of concurrency. > In the meantime, is there anywhere, or any thing, that discusses the > various concurrency options related to Python? There's Stackless Python > (which I can't make head or tail of; I have been unable to find any > lucid overview, or genuine explanation of the purpose of the design.) What about this introduction...? http://members.verizon.net/olsongt/stackless/why_stackless.html > I know that there's a package for an Erlang system for Python, somewhere > ("Parnassus" probably). There's probably a Py-CSP somewhere too. Lots > of trees, but where's the Wood? Here are some fairly similar projects in Python: http://kamaelia.sourceforge.net/ - a way of making general concurrency easy to work with, and fun http://candygram.sourceforge.net/ - a Python implementation of Erlang concurrency primitives http://www.python.org/pypi/parallel - process forking and channel-based communication (using pickles) > Where are concurrency/distributed models compared and discussed? In the following article and comments there are some opinions expressed on Python concurrency (along with the usual dose of Ruby vapourware promotion): http://www.oreillynet.com/onlamp/blog/2005/10/does_python_have_a_concurrency.html Meanwhile, the topic has been discussed on python-dev: http://mail.python.org/pipermail/python-dev/2005-September/056801.html That discussion led to a description of something which isn't so far from parallel/pprocess, at least: http://mail.python.org/pipermail/python-dev/2005-September/056829.html Other searching yielded this interesting paper about PyPy and "hardware transactional memory": http://portal.acm.org/citation.cfm?id=1176617.1176758&coll=ACM&dl=ACM&type=series&idx=1176617&part=Proceedings&WantType=Proceedings&title=Conference%20on%20Object%20Oriented%20Programming%20Systems%20Languages%20and%20Applications&CFID=15151515&CFTOKEN=6184618 Paul From mail at microcorp.co.za Sat Nov 4 00:09:15 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 4 Nov 2006 07:09:15 +0200 Subject: Is there a way to define a true global across modules? References: <005d01c6ff5e$2b5d95c0$03000080@hendrik> Message-ID: <002801c6ffcf$608cef40$03000080@hendrik> "Fredrik Lundh" wrote: > Hendrik van Rooyen wrote: > > > I am struggling with this - I want to define a "system-wide" flag for use as a > > semaphore. > > http://www.effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm > > Thanks - just like COBOL's data division *grin* - Hendrik From paul at boddie.org.uk Fri Nov 10 20:50:25 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Nov 2006 17:50:25 -0800 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <4554D416.70408@hobbshouse.org> <4554ECBF.7040603@hobbshouse.org> Message-ID: <1163209825.072410.203090@k70g2000cwa.googlegroups.com> Ron Adam wrote: > > PS. Rather than shav of on character her and ther in pythons programing > languag, Lets remov all the silent leters from the english languag. That will > sav thousands mor kestroks over a few yers. How about changing Python to support keywords and identifiers employing the Initial Teaching Alphabet? http://en.wikipedia.org/wiki/Initial_Teaching_Alphabet ;-) Paul From mail at microcorp.co.za Sat Nov 4 00:25:48 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 4 Nov 2006 07:25:48 +0200 Subject: Is there a way to define a true global across modules? References: <005d01c6ff5e$2b5d95c0$03000080@hendrik> Message-ID: <006601c6ffd1$b038d480$03000080@hendrik> "robert" wrote: > Fredrik Lundh wrote: > > Hendrik van Rooyen wrote: > > > >> I am struggling with this - I want to define a "system-wide" flag for > >> use as a > >> semaphore. > > > > http://www.effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm > > > > Or worse style - if you are too lazy to create a extra global variables module (ab)use the __main__ module als "global": > > > import __main__ > > __main__.mysemphore += 1 > > > -robert Thanks - how could you possibly have guessed that I am lazy - does it show that much? *WEG* - Hendrik From bignose+hates-spam at benfinney.id.au Wed Nov 8 07:23:29 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 08 Nov 2006 23:23:29 +1100 Subject: for x in... x remains global References: Message-ID: <87k626m8ji.fsf@benfinney.id.au> Antoine De Groote writes: > for x in range(3): pass > > After this statement is executed x is global variable. Not exactly. The name 'x' is bound at the scope of the 'for' statement, and remains bound after the 'for' statement stops, just as it would be if it was bound in any other statement. > This seems very unnatural to me and caused me 3 three days of > debugging because I was unintentionally using x further down in my > program (typo). This is, when used intentionally, one of the main useful features of this behaviour: to determine where an iteration stopped by using the value bound to the name ('x' in this case) after the iteration statement. > I would have thought that variables like this are local to the for > block. They're bound at the scope of the 'for' statement. They're available inside the suite of that statement. > Is there a reason this is not the case? Maybe there are PEPs or > something else about the matter that you can point me to? This message addresses it: A search for the separate terms "python iteration variable scope" will turn up more. -- \ "The best way to get information on Usenet is not to ask a | `\ question, but to post the wrong information." -- Aahz | _o__) | Ben Finney From fuzzyman at gmail.com Wed Nov 29 09:41:21 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Nov 2006 06:41:21 -0800 Subject: odict the Ordered Diction 0.2.2 Message-ID: <1164811281.405346.227240@l12g2000cwl.googlegroups.com> After a break of almost a year there has been an update to `odict the Ordered Dictionary `_. The latest version is 0.2.2, with changes implemented by Nicola Larosa. Despite over 700 downloads since May (plus 1300 as part of `pythonutils `_) there have been no bug reports, only improvements [#]_. {sm;:-)} * `Quick Download `_ What is odict? ========== **odict** is a pure Python implementation of an ordered dictionary. It keeps keys in insertion order and allows you to change the order. Methods (including iteration) that would return members in an arbitrary order are now ordered. There is also the `SequenceOrderedDict `_ that behaves like a sequence as well as a dictionary. It allows slicing and the keys, values and items methods are special sequence objects (which are also callable and so behave as methods too). What's New ? ========== Code ------- Removed the TODO and CHANGELOG sections in the tail docstring (they are in the docs anyway). Disabled warnings during tests. Explicitly disabled tests execution on Python v.2.2 . In addition to the slicing tests, other ones are failing. Removed code duplication between the ``__init__`` and the ``update`` methods. Misc. cleanup. Also, based on code from `Tim Wegener`_: - added the ``rename`` method; - removed a ``has_key`` usage in the ``__setitem__`` method. Documentation ---------------------- Moved the ISSUES chapter from code's tail docstring to here. Moved up the `Creating an Ordered Dictionary `_ chapter. Added prompts to the code examples and removed the superfluous print statements (sometimes they were there, sometimes they were not). Misc. cleanup. .. [#] So either no-one is using it, or it's really good... From steve at holdenweb.com Fri Nov 3 08:21:00 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Nov 2006 13:21:00 +0000 Subject: SE 2.3 temporarily unavailable. Cheese shop defeats upload with erratic behavior. Urgently requesting help. In-Reply-To: <454A4E1D.8030106@vtxmail.ch> References: <4549FA01.4090706@vtxmail.ch> <200611021020.31599.inq1ltd@verizon.net> <454A4E1D.8030106@vtxmail.ch> Message-ID: <454B423C.20400@holdenweb.com> Frederic Rentsch wrote: > jim-on-linux wrote: > >>Frederic, >> >>I've been trying to get back into my package in >>the Cheese Shop for over a year. The phone >>company changed my e:mail address and to make a >>long and frustrating story short I can't get back >>into the Cheese Shop to make changes to my file. >> >>Time is money. At some time you have to consider >>if it is worth it. At least you have the name of >>your program listed. >> >>I wish I could be more helpfull. I'll watch the >>responses you get from others. >> >>Good Luck, >>jim-on-linux >> >>http://www.inqvista.com >> >> >> >> >> >> >>On Thursday 02 November 2006 09:00, you wrote: >> >> >>>Some time ago I had managed to upload a small >>>package to the Cheese Shop using the data entry >>>template. Uploading is in two steps: first the >>>text then the package file. When I had a new >>>version it went like this: The new text made a >>>new page, but the new file went to the old >>> >> >>snip >> > > > > Thanks for letting me know that I am not alone. Do you know of an > alternative to the Cheese Shop? > Surely the correct answer to this problem is to get the Cheese Shop fixed, not to migrate away from it? To whom (besides this list) have you communicated the problem, and with what results? Remember that python.org is run by volunteers, but they are mostly highly capable volunteers. This is probably just a change situation that wasn't anticipated in the design (we all make mistakes). A simple change of email address could probably be achieved by tweaking the data for one or two individuals, and an automated solution should clearly be added as volumes build up. For now, how about a link that causes someone to receive email? I'd be surprised if this couldn't be used to handle low-volume changes with adequate security. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From cjw at sympatico.ca Tue Nov 7 22:14:02 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 07 Nov 2006 22:14:02 -0500 Subject: __init__ function problem In-Reply-To: <1162929803.735097.279460@i42g2000cwa.googlegroups.com> References: <1162905967.354604.38230@k70g2000cwa.googlegroups.com> <1162929803.735097.279460@i42g2000cwa.googlegroups.com> Message-ID: Carl Banks wrote: > kelin,zzf818 at gmail.com wrote: >> It says the __init__ is called immediately after an instance of the >> class is created. What dose "immediately" mean? >> And what is difference between the init method and the constructor in >> Java? > > For all intents and purposes, __init__ is a constructor. It isn't > technically, but you use it exactly the same way you use constructors > in C++ and Java (well, acutally, Python __init__ is a quite bit more > flexible, though also less convenient in many cases). Don't worry that > it isn't called a constructor. > > In Python, the real constructor is called __new__, but you shouldn't > use __new__ like C++ and Java constructors. Usually there's no reason > to use __new__ at all. (The main use case is to return something other > than a newly created object, such as a preallocated or cached object. > For your normally functioning classes, you should use __init__.) numpy.ndarray is an exception. There, one must call __new__, or a factory function which does the same thing. Colin W. > > > Carl Banks > From steve at REMOVE.THIS.cybersource.com.au Thu Nov 2 08:10:55 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 03 Nov 2006 00:10:55 +1100 Subject: best way to check if a file exists? References: <1162383348.925961.231160@h48g2000cwc.googlegroups.com> <1162390455.727684.118970@b28g2000cwb.googlegroups.com> Message-ID: On Thu, 02 Nov 2006 01:44:25 +1100, Ben Finney wrote: > "wittempj at hotmail.com" writes: > >> Ben Finney wrote: >> > "wittempj at hotmail.com" writes: >> > > You could try to read the file, if that fails it doesn't exist: >> > >> > Except that there are other conditions than "File doesn't exist" >> > that can cause an 'open' to fail. >> >> Ok, true. You can test explicit on non existence as follows, and then >> decide to open the file > > Or you can simply use 'os.path.exists', as has been suggested several > times in this thread. But there can be a race condition between os.path.exists returning True and you trying to open the file, if some other process deletes or renames the file in the meantime. -- Steven. From fredrik at pythonware.com Sat Nov 18 01:51:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 18 Nov 2006 07:51:19 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: <455E5C61.5030502@v.loewis.de> References: <455CED78.1060604@v.loewis.de> <455CF4BA.1050608@v.loewis.de> <1163759435.551233.76030@j44g2000cwa.googlegroups.com> <455E5C61.5030502@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> How about returning two lists, first list contains unicode names, the >> second list contains undecodable names: >> >> files, troublesome = os.listdir(separate_errors=True) >> >> and make separate_errors=True by default in python 3.0 ? > > That would be quite an incompatible change, no? it also violates a fundamental design rule for the standard library. From juho.schultz at pp.inet.fi Fri Nov 17 08:38:36 2006 From: juho.schultz at pp.inet.fi (Juho Schultz) Date: 17 Nov 2006 05:38:36 -0800 Subject: String Replace only if whole word? In-Reply-To: References: Message-ID: <1163770716.864547.10460@k70g2000cwa.googlegroups.com> Michael Yanowitz wrote: > Hello: > > I am hoping someone knows if there is an easier way to do this or someone > already implemented something that does this, rather than reinventing the > wheel: > I have been using the string.replace(from_string, to_string, len(string)) > to replace names in a file with their IP address. > For example, I have definitions file, that looks something like: > 10.1.3.4 LANDING_GEAR > 20.11.222.4 ALTIMETER_100 > 172.18.50.138 SIB > 172.18.50.138 LAPTOP > 172.18.51.32 WIN2000 > 127.0.0.1 LOCALHOST > > and I have a text file (a Python script) that has these names in the file. > In most cases the string.replace() command works great. But there is one > instance which it fails: > Suppose I had in the file: > if (LAPTOP_IS_UP()): > It would replace the string with: > if ("172.18.50.138"_IS_UP()): > > Is there any easy way to avoid this, only replace if a whole word > matches? > I probably need something which determines when a word ends, and I will > define > a word as containing only 'A'-'Z','a'-'z','0'-'9','_' . As long as the > string > contains more of the word digits after the match, don't replace? > > Thanks in advance: > Michael Yanowitz You need regular expressions for this. Use the re module. http://docs.python.org/lib/module-re.html from the docs: re.sub(pattern, repl, string[, count]) Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. Your pattern would be "[^A-Za-z0-9_]word[^A-Za-z0-9_]" [^xy] is approximately not in ('x', 'y') -- Juho Schultz From paul at boddie.org.uk Fri Nov 10 15:33:11 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Nov 2006 12:33:11 -0800 Subject: newbie: minidom References: Message-ID: <1163190791.312285.26230@h54g2000cwb.googlegroups.com> Danny Scalenotti wrote: > I'm not able to get out of this ....... > > > from xml.dom.minidom import getDOMImplementation > > impl = getDOMImplementation() // default UTF-8 > doc = impl.createDocument(None, "test",None) > root = doc.documentElement Here, you're actually getting a reference to the root "test" element at the top of the document. > root.setAttribute('myattrib', '5') > > print root.toxml() Here, you're serialising the root "test" element, not the whole document. > I obtain > > ...which is the expected result. > why not this? > > > Because you need to do this: print doc.toxml() Paul From do-not-reply at by-mail.com Fri Nov 17 05:12:41 2006 From: do-not-reply at by-mail.com (Johan von Boisman) Date: Fri, 17 Nov 2006 11:12:41 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: References: Message-ID: Laurent Pointal wrote: > gabor a ?crit : >> hi, >> >> from the documentation (http://docs.python.org/lib/os-file-dir.html) for >> os.listdir: >> >> "On Windows NT/2k/XP and Unix, if path is a Unicode object, the result >> will be a list of Unicode objects." > > Maybe, for each filename, you can test if it is an unicode string, and > if not, convert it to unicode using the encoding indicated by > sys.getfilesystemencoding(). > > Have a try. > > A+ > > Laurent. Strange coincident, as I was wrestling with this problem only yesterday. I found this most illuminating discussion on the topic with contributions from Mr L?vis and others: http://www.thescripts.com/forum/thread41954.html /johan From u2567446 at anu.edu.au Mon Nov 27 19:33:07 2006 From: u2567446 at anu.edu.au (Thuan Seah Tan) Date: Tue, 28 Nov 2006 11:33:07 +1100 Subject: Python script and C++ Message-ID: <456b83c7$1@clarion.carno.net.au> Hi all, I am new to python and currently I am working on a traffic simulation which I plan to define the various agents using scripting. It's kind of like scripting for non-playable character in games. I am thinking of using python for this but I am concerned with running time. Is scripting a lot slower compared to direct implementation in C++? Does compiling the script help in any way? Also, can anyone recommend me a book that covers python in general as well as C++ binding? Thanks. Thuan Seah Tan From bdesth.quelquechose at free.quelquepart.fr Thu Nov 23 17:31:51 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 23 Nov 2006 23:31:51 +0100 Subject: Trying to understand Python objects In-Reply-To: References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> <4565f8f7$0$8460$426a74cc@news.free.fr> Message-ID: <45661c32$0$28568$426a74cc@news.free.fr> Fredrik Lundh a ?crit : > Bruno Desthuilliers wrote: > >> Don't see it as a religious point please, but I fail to understand why >> you seem so in love with old-style classes ? (snip) > > to pick a few reasons: the old-style/new-style distinction is com- > pletely irrelevant for people new to the language, Until they try to use properties... From kaushalshriyan at gmail.com Mon Nov 6 06:12:34 2006 From: kaushalshriyan at gmail.com (kaushal) Date: 6 Nov 2006 03:12:34 -0800 Subject: Learning Python In-Reply-To: References: <1162803632.788766.147590@e3g2000cwe.googlegroups.com> <1162805615.944184.138050@h48g2000cwc.googlegroups.com> Message-ID: <1162811554.731349.145980@h48g2000cwc.googlegroups.com> On Nov 6, 2:54 pm, "Jorge Vargas" wrote: > On 6 Nov 2006 01:33:36 -0800, ArdPy wrote: > > > > > kaushal wrote: > > > Hi > > > > How do i start Learning Python,is there any reference material which I > > > can refer since I dont have > > > any programming experience > > > > Thanks and Regards > > > > Kaushal > > > Hi kaushal, > > > Look intohttp://diveintopython.org. Dive into python is a really > > readable ebook...enjoyEven though that's a great book I don't recomend it for non > programmers I think thishttp://docs.python.org/tut/is a better way > to start > > also I'll suggest you start learning other programming languaje before > python or else this will be the only one you will code :) > > > -- > >http://mail.python.org/mailman/listinfo/python-list Hi Just wanted to know how is this URL http://www.ibiblio.org/obp/thinkCSpy/ Thanks and Regards Kaushal From agriff at tin.it Mon Nov 6 16:09:49 2006 From: agriff at tin.it (Andrea Griffini) Date: Mon, 06 Nov 2006 22:09:49 +0100 Subject: Unicode/ascii encoding nightmare In-Reply-To: <1162846564.782883.259110@h54g2000cwb.googlegroups.com> References: <1162842650.780517.180360@b28g2000cwb.googlegroups.com> <1162846564.782883.259110@h54g2000cwb.googlegroups.com> Message-ID: <454fa3c9$0$13767$4fafbaef@reader3.news.tin.it> John Machin wrote: > The fact that C3 and C2 are both present, plus the fact that one > non-ASCII byte has morphoploded into 4 bytes indicate a double whammy. Indeed... >>> x = u"f?dselsdag" >>> x.encode('utf-8').decode('iso-8859-1').encode('utf-8') 'f\xc3\x83\xc2\xb8dselsdag' Andrea From cbarbez at gmail.com Sat Nov 11 05:51:05 2006 From: cbarbez at gmail.com (DarkPearl) Date: 11 Nov 2006 02:51:05 -0800 Subject: service windows avec py2exe In-Reply-To: References: <1163157344.987173.259940@i42g2000cwa.googlegroups.com> Message-ID: <1163242265.307783.122230@f16g2000cwb.googlegroups.com> I found the function which starts the error ********************************** class Win32ProcessUsage: def __init__(self): self.lstProcess=[] self.WMIService = win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") self.reset() def reset(self): self.lstProcess=[] lstTmp = self.WMIService.ExecQuery('Select * from Win32_Process') for item in lstTmp: self.lstProcess.append(tuple([item.Name,item.CommandLine,item.Status,item.ProcessId,item.ParentProcessId])) def get_usage(self): return self.lstProcess ********************************** it is a class which allows to obtain the list of the processes who run. With python interpreter, this class functions very well but , when it turns in service, it starts the error : The instance's SvcRun() method failed : (-2147221020, 'Syntaxe incorrecte', None, None) Why ??? From fredrik at pythonware.com Thu Nov 2 01:48:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 02 Nov 2006 07:48:32 +0100 Subject: CSV module, DictReader problem (bug?) In-Reply-To: References: <1162415232.190913.163240@m73g2000cwd.googlegroups.com> <1162434526.601605.315560@k70g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > if you're wrapping some cmd.exe command in an internal API, it's usually > easier to call "os.path.normpath" the last thing you do before you call > "os.system", than to get all the backslashes right in your code. > > also see: > > http://www.effbot.org/pyfaq/why-can-t-raw-strings-r-strings-end-with-a-backslash.htm and as just I pointed out in a comment on that page, getting the slashes right doesn't help you with spaces in filenames. to write reliable code for os.system, you want something like: import os.path import subprocess def mysystem(command, *files): files = map(os.path.normpath, files) files = subprocess.list2cmdline(files) return os.system(command + " " + files) mysystem("more", "/program files/subversion/readme.txt") but then you might as well use subprocess.call, of course. From fredrik at pythonware.com Tue Nov 14 06:40:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Nov 2006 12:40:37 +0100 Subject: Using signal.alarm to terminate a thread In-Reply-To: References: <12lgk7h55lu0vb4@corp.supernews.com> <12lj35aqa9drd8a@corp.supernews.com> Message-ID: Nick Craig-Wood wrote: > The only sensible things you can do from a signal handler is set a > global flag, or call sem_post on a semaphore, to record the delivery > of the signal. The remainder of the program can then either poll the > global flag, or use sem_wait() and sem_trywait() on the semaphore. but that's exactly what Python's signal handlers do, right ? (the interpreter uses a "pending call" queue to collect events, and executes them from the interpreter main loop in a controlled fashion). From ironfroggy at gmail.com Wed Nov 29 21:26:40 2006 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 29 Nov 2006 21:26:40 -0500 Subject: How to detect what type a variable is? In-Reply-To: <1164814586.113454.144090@l12g2000cwl.googlegroups.com> References: <1164814586.113454.144090@l12g2000cwl.googlegroups.com> Message-ID: <76fd5acf0611291826k4ada9725qfd0dea46b1c66c40@mail.gmail.com> On 29 Nov 2006 07:36:26 -0800, Leandro Ardissone wrote: > Hi, > > I want to know what type is a variable. > For example, I get the contents of an xml but some content is a list or > a string, and I need to know what type it is. > > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > In nearly all cases where someone asks this question, the situation turns out to not call for it at all. Usually you simply aren't thinking in the language you are using properly. You should usually know what you are dealing with. If you don't, then either the different types of objects you might have should be interchangable or you should create a situation where you dont have such an ambiguality. Perhaps you could change the design such that you always have a list, even if its just a list of a single string. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From fdu.xiaojf at gmail.com Mon Nov 6 20:41:29 2006 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Tue, 07 Nov 2006 09:41:29 +0800 Subject: sound process moduls in python ? Message-ID: <454FE449.3090204@gmail.com> Hi, When I was talking with my friend, I wanted to share the music I'm listening with my friend. I mean, I wanted my friend to hear my music and my own sound . I order to achieve this, I think I need to append the output of my sound card to the input of the sound card. My questions: 1. Is my idea possible ? 2. Which sound processing module is capable to do this ? The module should at least available at Windows platform. Thanks ! xiaojf From boris.smirnov at gmail.com Thu Nov 9 10:45:25 2006 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 9 Nov 2006 07:45:25 -0800 Subject: extract text from a string Message-ID: <1163087125.176931.296440@h54g2000cwb.googlegroups.com> Hallo all, I have tried for a couple of hours to solve my problem with re but I have no success. I have a string containing: "+abc_cde.fgh_jkl\n" and what I need to become is "abc_cde.fgh_jkl". Could anybody be so kind and write me a code of how to extract this text from that string? thank you very much in advance regards, boris From mike$#at^&nospam!%trauschus Fri Nov 3 21:20:56 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Fri, 03 Nov 2006 21:20:56 -0500 Subject: Converting Microsoft Works databases.... *shudder* In-Reply-To: References: Message-ID: <0cedncli_d2UZNbYnZ2dnUVZ_sGdnZ2d@comcast.com> Larry Bates wrote: > > MS ships ODBC interface to xBase databases in all versions of Windows. > You don't need Access. Just create DSN to your exported dBase database > and MS Word, MS Excel, and any other ODBC aware product can read the > data. If the data size is large or if you want to move to server, you > can do that later. > Oh! I hadn't realized that Win32 ODBC handled connections to dBase files. Learn something new every day... :-) Thanks! (I suppose that is something that I would probably know, if I used Windows...) -- Mike From nulla.epistola at web.de Sun Nov 19 11:59:49 2006 From: nulla.epistola at web.de (Hertha Steck) Date: Sun, 19 Nov 2006 17:59:49 +0100 Subject: How do I stop Python IDLE (GUI) from immediately exiting when I enter it? References: <1163921048.878108.145810@j44g2000cwa.googlegroups.com> Message-ID: Am Sat, 18 Nov 2006 23:24:08 -0800 schrieb John (Z R) L: > Hi all, I am very new to programming, and I chose to study the Python > language before C++. I am currently using the Wikibooks > "Non-Programmer's Tutorial for Python", and am up to the section "Who > goes there"? > > http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python/Who_Goes_There%3F > > But after clicking "run module" for > " > a = 1 > print a > a = a + 1 > print a > a = a * 2 > print a " > > The results "1, 2, 4" didn't appear on the GUI screen, in fact nothing > did. And I clicked twice again, this time, it exited the Python GUI > program. I tried to enter back in, but it would quickly display > > "1 > 2 > 4" > > before exiting immediately within half a second. How do I stop the this > exiting from occurring. > All of this using IDLE as your GUI (not PythonWin and not the python interpreter by itself), right? You did all this as explained at the start of the tutorial: open a "New window", type the code into this empty window, save it to a reasonable place and then click "Run / Run module". Right? (Silly question: there is no run menu in the interactive window. On the other hand, you never know.) What about the examples before this one, did you type, save and run them just like this one? And did they work as you expected? What version of Python and of IDLE do you use? If you have PythonWin (it's part of ActiveState Python, for example): what happens, if you run your script using that? What happens if you open a command window, go to the right directory and run your script from there? (Don't try to start it by double clicking in the explorer: it will run, but the window will close immediately afterwards, and you won't see anything.) > Another problem I have is firewall. On my old computer (Windows 98) > when using Python GUI, it can't run modules because of some firewall. > But I thought firewalls were for internet sites only?! How do I fix > this?? > Do you mean this? **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** This shouldn't keep any script from running. What exactly happens if you try? From pwatson at redlinepy.com Sat Nov 11 11:00:20 2006 From: pwatson at redlinepy.com (Paul Watson) Date: Sat, 11 Nov 2006 10:00:20 -0600 Subject: newbie: minidom In-Reply-To: References: Message-ID: <4555F394.80802@redlinepy.com> Fredrik Lundh wrote: > Danny Scalenotti wrote: > >> I'm not able to get out of this ....... >> >> from xml.dom.minidom import getDOMImplementation >> >> impl = getDOMImplementation() // default UTF-8 >> doc = impl.createDocument(None, "test",None) >> root = doc.documentElement >> root.setAttribute('myattrib', '5') >> >> print root.toxml() >> >> >> I obtain >> >> >> >> why not this? >> >> >> > > > why? the documents are equivalent, and any XML application that > requires an explicit UTF-8 encoding declaration is broken. > > Explicit is better than implicit. From cemerick at snowtide.com Sun Nov 19 10:08:38 2006 From: cemerick at snowtide.com (Chas Emerick) Date: Sun, 19 Nov 2006 10:08:38 -0500 Subject: lxml/ElementTree and .tail In-Reply-To: References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> <761846B7-E374-41FE-8804-CBB3D42FD4D2@snowtide.com> <1163835505.102190.140060@b28g2000cwb.googlegroups.com> <1163941421.235619.150260@f16g2000cwb.googlegroups.com> Message-ID: <6EBAFB85-4942-4C80-8BB4-8360583A3525@snowtide.com> On Nov 19, 2006, at 9:55 AM, Fredrik Lundh wrote: >> And oh by the way, this thread is all about *your* customer's >> complaining. > > from what I can tell, it was *your* customer posting FUD about a > different library, not my customer asking for help with a specific > problem. this is free software; people who use a piece of software > count a *lot* more than people who don't want to use it. Holy hell Fredrik -- I hadn't even *downloaded* 4suite before I posted my original question. I've tried to be nice, tried to be complimentary, and tried to be diplomatic, so it would be nice if *everyone* would stop casting aspersions or otherwise speculating about my intentions. Flame amongst yourselves, but leave me out of it. - Chas From carsten at uniqsys.com Tue Nov 14 10:44:38 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 14 Nov 2006 10:44:38 -0500 Subject: Noob | datetime question In-Reply-To: <77895c1d0611140733y1ab3d28dr8e542d51438a2cc@mail.gmail.com> References: <136ED738BD4F1545B97E4AC06FF6370734BFB6@DMSP-MSG-EVS01.mail.pvt> <77895c1d0611140733y1ab3d28dr8e542d51438a2cc@mail.gmail.com> Message-ID: <1163519078.3353.22.camel@dot.uniqsys.com> On Tue, 2006-11-14 at 09:33 -0600, Kevin Kelley wrote: > import time > FORMAT='%Y%m%d' > > time.strftime(FORMAT,time.gmtime(time.time()+8380800)) > output = '20070219' While the above works, the following variation using datetime is more readable: >>> import datetime >>> someday = datetime.date.today() + datetime.timedelta(days=97) >>> print someday.strftime("%Y%m%d") 20070219 -Carsten From deets at nospam.web.de Wed Nov 1 15:32:07 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 01 Nov 2006 21:32:07 +0100 Subject: scared about refrences... In-Reply-To: <1162412436.595926.66940@i42g2000cwa.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162251429.386255.289620@e3g2000cwe.googlegroups.com> <4547d0d7$0$7246$426a34cc@news.free.fr> <1162412436.595926.66940@i42g2000cwa.googlegroups.com> Message-ID: <4qsei4Foo2f6U1@uni-berlin.de> SpreadTooThin schrieb: > Bruno Desthuilliers wrote: >> Nick Vatamaniuc a ?crit : >> (snip) >>> In Python all the primitives are copied and all other entities are >>> references. >> Plain wrong. There's no "primitives" (ie : primitive data types) in >> Python, only objects. And they all get passed the same way. > > so.. > def fn(x): > x = x + 1 > print x > > a = 2 > fn(a) > fn(2) > > Wouldn't you say that this is being passed by value rather than by > refrence? It appears so, but it still is a truth - all objects, even the numbers, are objects. No copying. Diez From pydecker at gmail.com Sat Nov 4 11:47:09 2006 From: pydecker at gmail.com (Peter Decker) Date: Sat, 4 Nov 2006 11:47:09 -0500 Subject: python GUIs comparison (want) In-Reply-To: <1162657420.655675.185930@e3g2000cwe.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <1162657420.655675.185930@e3g2000cwe.googlegroups.com> Message-ID: On 4 Nov 2006 08:23:40 -0800, Mudcat wrote: > I have been using Tkinter for several years now. Recently I have been > thinking about switching to something else that may have a sharper > appearance. However I'm not sure what that may be, and if that > something else is *that* much better than what I'm already using. > > Does everyone agree that wxPython looks best on Windows? I've also read > in a couple of places where Dabo looks pretty good as well. Dabo uses wxPython, so it looks exactly the same. The difference is in the coding: writing stuff in wxPython is like writing C++ code, while creating GUIs in Dabo is like writing Python code. Dabo also has a lot of tools for creating GUIs visually, but even if you don't use those, Dabo is a huge improvement over raw wxPython. -- # p.d. From usenet1 at anton.e4ward.com Tue Nov 7 10:18:52 2006 From: usenet1 at anton.e4ward.com (Anton81) Date: Tue, 07 Nov 2006 16:18:52 +0100 Subject: __div__ not recognized automatically References: Message-ID: > If you have the > > from __future__ import division > > statement, you need to override __truediv__(), not __div__() That worked after I also added from __future__ import division to all other modules I created. Is it possible that there appears an inconsistency if the division is imported in only some of the modules? Anton From __peter__ at web.de Thu Nov 9 08:29:44 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Nov 2006 14:29:44 +0100 Subject: newbie class-building question References: <1163075427.630088.247050@h54g2000cwb.googlegroups.com> Message-ID: jrpfinch wrote: > I am constructing a simple class to make sure I understand how classes > work in Python (see below this paragraph). > > It works as expected, except the __add__ redefinition. I get the > following in the Python interpreter: > >>>> a=myListSub() >>>> a > [] >>>> a+[5] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'str' object is not callable >>>> > > Please could you let me know where I am going wrong. I have hacked > around with the code and tried googling this error message but am > having difficulty finding the source of the problem. > class myList: > def __init__ (self,value=[]): > self.wrapped=[] > for x in value : > self.wrapped.append(x) > def __repr__ (self): > return `self.wrapped` > def __getattr__ (self,attrib): > return getattr(self.wrapped,attrib,'attribute not found') When Python is looking for an attribute that neither exists in myList nor the 'wrapped' list, you give back a string. In your case this happens for the __coerce__() method, and the interpreter ends up calling "attribute not found" which of course must fail. The solution: - Don't provide a bogus default for getattr(), and get a traceback that is easier to understand. - Use new-style classes (i.e. class myList(object): ...) which look for special methods in the class, not the instance. Peter From dlenski at gmail.com Thu Nov 9 16:01:51 2006 From: dlenski at gmail.com (Dan Lenski) Date: 9 Nov 2006 13:01:51 -0800 Subject: How to choose the right GUI toolkit ? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> Message-ID: <1163106111.916021.103880@b28g2000cwb.googlegroups.com> Wojciech Mula wrote: > Nick Craig-Wood wrote: > >> It's very mature, full-featured, and portable, and fairly easy to > >> learn as well. > > > > ...with native look and feel on each platform unlike GTK / TK > > AFAIK Tk 8 uses platform's native widgets. > > w. Tk 8.4 appears to use native Win32 widgets under Cygwin and native WinXP. But it definitely doesn't use GTK widgets under Ubuntu with Gnome desktop. Is there a way to get it to do so? Dan From steve at holdenweb.com Fri Nov 10 16:06:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Nov 2006 15:06:26 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: <2006111015340116807-jameshcunningham@gmailcom> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> <4rjlkqFrlskqU1@mid.individual.net> <4rk5giFrerjfU1@mid.individual.net> <2006111015340116807-jameshcunningham@gmailcom> Message-ID: James Cunningham wrote: > On 2006-11-10 15:24:50 -0500, Bjoern Schliessmann > said: > >> Marc 'BlackJack' Rintsch wrote: >> >>> No it doesn't -- look again at the example given above. It's >>> legal syntax in Python but doesn't have the semantics implied by >>> the example. >> Sorry, I don't understand -- what is the difference between the >> example as it is and the implied semantics of it? >> >> Regards, >> >> >> Bj?rn > > Yes, I'm not sure myself. > > In [1]: color = "red" > > In [2]: if color == "red" or "blue" or "green": > ...: print 'Works.' > ...: > ...: > Works. > > In [3]: if color == "blue" or "red" or "green": > ...: print 'Works.' > ...: > ...: > Works. > > In [4]: if not color == "blue" or "green": > ...: print 'Works.' > ...: > ...: > Works. > Try testing a little more completely: >>> for color in ('blue', 'red', 'green', 'yellow'): ... if color == 'blue' or 'red' or 'green': ... print color, "compares true" ... else: ... print color, "compares false" ... blue compares true red compares true green compares true yellow compares true >>> Still think it works? >>> print 'yellow' == 'blue' or 'red' or 'green' red >>> print 'blue' == 'blue' or 'red' or 'green' True >>> Now do you understand why it doesn't work? Think "operator precedence". regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From skip at pobox.com Tue Nov 14 10:51:14 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 14 Nov 2006 09:51:14 -0600 Subject: Random image text generation? In-Reply-To: <7xslgmxo94.fsf@ruckus.brouhaha.com> References: <7xslgmxo94.fsf@ruckus.brouhaha.com> Message-ID: <17753.58866.541188.422704@montanaro.dyndns.org> >>>>> "Paul" == Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: Paul> Steven D'Aprano writes: >> Instead of displaying an obfuscated image of a nonsense word, display >> six randomly chosen photos, where five are of the same thing but not >> the same image. E.g. you might show five different kittens and a >> horse. The user has to click on the image that is not the same as the >> others. State-of-the-art horse-recognition software is not yet in >> widespread use by spammers *wink* Paul> No need to recognize the horse. Just pick one of the pictures at Paul> random and you'll get the right one 1/6th of the time. Repeat ad Paul> infinitum--they're spammers and like to repeat stuff after all. Paul> That's why those conventional captcha images make you recognize a Paul> multi-character string: so the guessing chance is low. Actually, the ones I saw that used a set of "one of these things is not like the other" images gave you a pop-up menu of maybe 100-200 words. The user needed to choose the name of the different object from that list. That makes it a bit harded to guess. Of course, these sorts of tests suffer from the same shortcoming as the randomly generated string. Visually impaired people have trouble with it. I finally settled on just reusing the SpamBayes engine to detect/reject spam submissions. Skip From dhable at gmail.com Fri Nov 10 15:30:57 2006 From: dhable at gmail.com (dhable at gmail.com) Date: 10 Nov 2006 12:30:57 -0800 Subject: Modules, Packages and Developer Confusion. Oh My! Message-ID: <1163190657.792705.55030@m73g2000cwd.googlegroups.com> I think I'm still missing something in how python is handling packages and it's mixing me up. I have a package with three files (modules?) like so: OPS:\ __init__.py model.py search.py To hide more details of the package structure, I import model and search inside of __init__. It also seemed like a good idea to define a global function that creates a database connection and I added it to __init__.py. Thus, I have: from model import * from search import * def create_connection(): # details are unimportant for this example When I try to use the create_connection function in model, I get errors when I use it as a global function ( just create_connection()). The only way to resolve the error was to import OPS inside of model and use OPS.create_connection(). This doesn't seem natural. If model is part of OPS, why do I need to tell python to import OPS and use this function from OPS? I can see doing that from the outside world, but inside? Any clarification would be greatly appreciated. From fredrik at pythonware.com Thu Nov 30 13:31:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 30 Nov 2006 19:31:33 +0100 Subject: Trying to understand rfc822.Message() behaviour In-Reply-To: <1164910937.624693.315950@l12g2000cwl.googlegroups.com> References: <1164910937.624693.315950@l12g2000cwl.googlegroups.com> Message-ID: Phoe6 wrote: > Have a look at this snippet, I have a file direct.txt and I want to > read it as rfc8222.Message() so that I get the Subject: and Mood: as > Dict Keys and content separately, but I am unable to get the Content > Properly. > >>>> fhandle = open('direct.txt','r') >>>> print fhandle.read() > Subject: testing - fortune > Mood: happy > > > "Why should we subsidize intellectual curiosity?" > - Ronald Reagan > > >>>> fhandle.seek(0) >>>> import rfc822 >>>> message = rfc822.Message(fhandle) >>>> print message > Subject: testing - fortune > Mood: happy > > > What is happening here. Why is the message not coming up? because the rfc822.Message parser only reads the header; to read the rest, just call "read" on the file object after you've parsed the header. see http://effbot.org/librarybook/rfc822.htm for some sample code. From lycka at carmen.se Thu Nov 2 07:04:27 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 02 Nov 2006 13:04:27 +0100 Subject: Event driven server that wastes CPU when threaded doesn't In-Reply-To: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> References: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> Message-ID: Snor wrote: > I'm attempting to create a lobby & game server for a multiplayer game, > and have hit a problem early on with the server design. I am stuck > between using a threaded server, and using an event driven server. I've > been told time and time again that I should use an event driven server > design (that is, use twisted). [snip] > Is the only solution to use a threaded server to let my clients make > their requests and receive a response in the fastest possible time? You got a lot of long-winded replies, but the short reply is that Twisted has packaged solutions for this. See http://twistedmatrix.com/projects/core/enterprise "Twisted provides an interface to any Python DB-API 2.0 compliant database through an asynchronous interface which allows database connections to be used, and multiplexed by multiple threads, while still remaining thread-safe for use with Twisted's event-based main loop. Twisted Enterprise provides these services by leveraging Twisted Internet's utilities for managing thread pools and asynchronous programming." From irmen.NOSPAM at xs4all.nl Sun Nov 5 07:25:45 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 05 Nov 2006 13:25:45 +0100 Subject: Pyro stability In-Reply-To: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> Message-ID: <454dd84b$0$328$e4fe514c@news.xs4all.nl> writeson wrote: [some questions about Pyro] I've replied to this on Pyro's mailing list. -Irmen From DustanGroups at gmail.com Sat Nov 11 19:15:26 2006 From: DustanGroups at gmail.com (Dustan) Date: 11 Nov 2006 16:15:26 -0800 Subject: reduce to be removed? In-Reply-To: References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163288885.884417.218270@f16g2000cwb.googlegroups.com> Message-ID: <1163290526.013063.245130@m7g2000cwm.googlegroups.com> Fredrik Lundh wrote: > Dustan wrote: > > > Because I'm embedding this expression in a list comprehension > > because? > > Because I thought I would be able to get an answer without revealing the exact details of what I am doing. I didn't realize that wasn't an option. I'll try once more to give you an idea of what I'm trying to accomplish without letting on the details. >>> foo =\ [[[1,2,3],[4,5,6],[7,8,9]], [[3,2,1],[6,5,4],[9,8,7]]] Here, foo appears to be a 3-dimensional list - except it's supposed to be 2-dimensional. The inner-list-of-lists is a result of how I'm producing the data, and now I want to do a mass-concatenation (or extending) of the inner-list-of-lists, and come up with this: >>> foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]] True What's the best way to accomplish this? It's not quite this simple, but let's just see what you can come up with the information at hand, and I'll see if I can adapt it to my needs. From joel.hedlund at gmail.com Sat Nov 11 06:32:52 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Sat, 11 Nov 2006 12:32:52 +0100 Subject: import parser does not import parser.py in same dir on win Message-ID: Hi! I have a possibly dumb question about imports. I've written two python modules: parser.py ------------------------------------ class Parser(object): "my parser" ------------------------------------ app.py ------------------------------------ from parser import Parser print "import successful" ------------------------------------ Running app.py on linux, gives: ------------------------------------ import succesful ------------------------------------ However, runnning it on windows gives: ------------------------------------ Traceback (most recent call last): File "test.py", line 1, in ? from parser import Parser ImportError: cannot import name Parser ------------------------------------ It turns out that on Windows, the builtin parser module is imported instead. Why? Why is there a difference? What other names are "taken"? In both cases the script dir is first on sys.path, and I'm using the plain old terminal/cmd window. Thanks for your time. Cheers! /Joel Hedlund From sjmachin at lexicon.net Sun Nov 26 05:00:09 2006 From: sjmachin at lexicon.net (John Machin) Date: 26 Nov 2006 02:00:09 -0800 Subject: search versus match in re module In-Reply-To: <1164528934.695210.220500@j44g2000cwa.googlegroups.com> References: <1164291336.523872.131610@h54g2000cwb.googlegroups.com> <4565BC89.9060901@mac.com> <7.0.1.0.0.20061124234209.03442fe0@yahoo.com.ar> <4567B532.4030906@mac.com> <7.0.1.0.0.20061125034101.01f7acb0@yahoo.com.ar> <1164528934.695210.220500@j44g2000cwa.googlegroups.com> Message-ID: <1164535209.879458.119180@h54g2000cwb.googlegroups.com> John Machin wrote: [snip] > 2. Then realise that your test is equivalent to > > if not line.startswith('^From '): Whoops! That '^From ' (and all later ones) should have been 'From ' (the perils of over-hasty copy/paste) The timings are, if anything, a tiny bit faster than before. Cheers, John From irmen.NOSPAM at xs4all.nl Wed Nov 8 19:11:36 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 09 Nov 2006 01:11:36 +0100 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: <87slgt1vmh.fsf@gmail.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> <87slgt1vmh.fsf@gmail.com> Message-ID: <4552723b$0$323$e4fe514c@news.xs4all.nl> Jorge Godoy wrote: > Cliff Wells writes: > >> I think this sums up my point of view as well (although I would have >> used around 3215 more words to say it). > > Hmmmm... Putting this on the discussion of the week: you'd have used > range(3215) or xrange(3215) more words? ;-) > Actually I've just replaced a loop in Pyro from using range to using xrange because of memory issue when you wanted to run it nearly indefinitely. So there. Finally back on the original subject ;-) Thanks for the praise about Pyro but yeah, I would have been equally happy if it was put without using the f word :) Cheers --Irmen. From saptarshi.guha at gmail.com Wed Nov 8 23:27:01 2006 From: saptarshi.guha at gmail.com (sapsi) Date: 8 Nov 2006 20:27:01 -0800 Subject: Using Python from Cocoa App via PyObjc - numbers dont match... In-Reply-To: <1163042247.489957@nfs-db1.segnet.com> References: <1163035378.654266.287360@m73g2000cwd.googlegroups.com> <1163042247.489957@nfs-db1.segnet.com> Message-ID: <1163046421.638588.222350@i42g2000cwa.googlegroups.com> Hi, Well not a complaint as such but a question. Thank you for the response however and the link. I have seen it before but never got around to reading it... Further to this, if i was writing a python module and c function and suppose the python module and the c function called each other back and forth exchanging results from float calculations - would not the results then become flawed? How would one pass floats between different languages - using special purpose data structures understood by both the python module and c code? I asked this question without reading the link, so if it stinks of ignorance please forget it. Thank you Saptarshi Michael Ash wrote: > In comp.lang.objective-c sapsi wrote: > > The first output in the console is 40.4 and the second > > -40.40000152587891. > > > > If i change the NSLog(s) to "%f",[n floatValue] (and the second > > likewise) the first is 40.400002 and the second is -40.400002. > > I assume you are complaining about the fact that it's not printing exactly > 40.4, and wondering where the error is coming from. (It helps if you > actually state this yourself, so we don't have to assume it, rather than > just laying out the circumstances.) > > The answer is that floating point numbers are inherently imprecise. Read > through this essential resource: > > http://docs.sun.com/source/806-3568/ncg_goldberg.html > > -- > Michael Ash > Rogue Amoeba Software From fredrik at pythonware.com Thu Nov 23 06:05:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Nov 2006 12:05:07 +0100 Subject: How do I separate my parameters with spawnv In-Reply-To: References: Message-ID: Fabio Chelly wrote: > But when I try to use os.spawnv to excute it from my python code, it > doesn't work at all. Here is my code: > > exe = "c:\\curl.exe" > f = "c:\\upload.txt" > logon = "login:pwd" > url = "ftp://ftp-myurl" > import os > os.spawnv(os.P_WAIT, exe, ["-T", f, "-u", logon, url, "--ftp-ssl"]) iirc, spawnv expects an argv-style list, with the program name as the first argument. try writing the above as os.spawnv(os.P_WAIT, exe, [exe, "-T", f, "-u", logon, url, "--ftp-ssl"]) > Does anyone know How I can execute my command line in python? the subprocess module is usually much nicer for things like this. From johnjsal at gmail.com Thu Nov 2 15:50:04 2006 From: johnjsal at gmail.com (JohnJSal) Date: 2 Nov 2006 12:50:04 -0800 Subject: what's the difference between these two methods? (aka, why doesn't one of them work?) In-Reply-To: References: <1162499293.080529.5480@m73g2000cwd.googlegroups.com> Message-ID: <1162500604.198685.97710@i42g2000cwa.googlegroups.com> Peter Otten wrote: > ...the above is not a 1-tuple, but an ordinary string. You forgot the > trailing comma: > > ('notes',) Right you are! Now it works! :) Thanks! From arkanes at gmail.com Tue Nov 21 13:56:25 2006 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 21 Nov 2006 12:56:25 -0600 Subject: How good is CORBA? In-Reply-To: <45634A59.5080501@wiggly.org> References: <6559fb300611211036l306e99d6ibd354dcd285b243@mail.gmail.com> <45634A59.5080501@wiggly.org> Message-ID: <4866bea60611211056r6e1e514cw5798c24674f6c685@mail.gmail.com> On 11/21/06, Nigel Rantor wrote: > Sai Krishna M wrote: > > Hi everybody, > > > > i have been developing web based applications using python+cheetah. > > > > The numbers are increasing. The applications have many common parts of > > code. Though these applications are separate from each other they are > > run in the same server. > > > > I heard about CORBA... but also heard that it has some flaws...like > > the programming being very complicated. > > Also heard that CORBA is no more used these days... > > > > Can someone suggest me a better option or is corba fine? > > This is an extremely loaded question and you're liable to get many > differing opinions. > > What follows is just my opinion, I don't want to get into any religious > wars. > > CORBA is a large, complex system that allows you to do object-RPC > efficiently and in many different languages. > > Web services are now converging on the same solutions as the OMG did > with CORBA because they are solving the same problems. > > If you need to access someone else's services then web services with > XML-RPC/SOAP/REST is probably a great idea. > > If you have any kind of need for performance, or if all of your > interfaces are internal then I would choose CORBA. > > I am currently building a system with a mixture of CORBA/SOAP interfaces > because of these trade-offs. > > If you don't like CORBA, but want to do efficient object-RPC and don't > mind paying for it then perhaps look at Ice from www.zeroc.com, they're > a bunch of good guys who were big CORBA people and decided to go make an > object-RPC mechanism without the cruft that CORBA gathered. > FYI: Ice is available under the GPL, so if by "pay" you mean "pay money" that's not your only option. You can also get a commercial license, similiar to Qt. I like Ice a lot, it's got hardly any of the ramp up time and learning curve that CORBA does, and it's extremely efficent. If GPL or cash are acceptable licensing options to you, then I encourage you to use it before you head to CORBA. > Despite the fact that some very bad decisions were made about what to > include in CORBA you don't *have* to use any of the braindead features. > > If you have any more specific questions then let me know, this is just > my quick 0.02c > > Regards, > > n > > -- > http://mail.python.org/mailman/listinfo/python-list > From ytlim1 at gmail.com Fri Nov 17 07:37:03 2006 From: ytlim1 at gmail.com (Why Tea) Date: 17 Nov 2006 04:37:03 -0800 Subject: What python modules are available? In-Reply-To: References: <1163765733.745577.116670@m73g2000cwd.googlegroups.com> Message-ID: <1163767023.599564.260920@m7g2000cwm.googlegroups.com> > http://svn.effbot.python-hosting.com/pydotorg/listmodules/listmodules.py Thanks. The script worked nicely. > > I tried to import numarray, but python couldn't find it. > > numarray isn't a standard module; see the library reference for a list > of modules that you can expect to be available on most platforms (but > make sure you check the page for the modules you're interested in, to All I need is something to provide me with array features. I can't remember why I chose to use numarray a while ago... From sjmachin at lexicon.net Thu Nov 30 19:26:09 2006 From: sjmachin at lexicon.net (John Machin) Date: 30 Nov 2006 16:26:09 -0800 Subject: String formatters with variable argument length References: Message-ID: <1164932769.210948.289560@f1g2000cwa.googlegroups.com> Fredrik Tolf wrote: > I've been trying to get the string formatting operator (%) to work with > more arguments than the format string requires, but I can find no way to > do that. For example: > > >>> "%i" % 10 > '10' > >>> "i" % 10 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: not all arguments converted during string formatting > > The thing is, I want to get format strings from the user, and I don't > want to require the user to consume all the arguments. docs.python.org > doesn't seem to have any clues on how to achieve this, and I can't think > of what to google for. > > Could it be as I fear, that it is impossible? > Three approaches spring to mind. In descending order of my preference: (a) don't do that (b) parse the format string, counting the number of args required. If the user has supplied more, throw them away. (c) wrap your execution of format_string % args in a try/except bracket. If you get a TypeError with that message [not guaranteed to remain constant in the future], throw away the last arg and go around again. As a matter of curiosity, why don't you want the user to consume all the arguments? Don't they get even a teensy-weensy warning message? Are you writing a Perl interpreter in Python? Cheers, John From apardon at forel.vub.ac.be Mon Nov 13 05:27:05 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Nov 2006 10:27:05 GMT Subject: str.title question after ' Message-ID: I have a text in ascii. I use the ' for an apostroph. The problem is this gives problems with the title method. I don't want letters after a ' to be uppercased. Here are some examples: argument result expected 't smidje 'T Smidje 't Smidje na'ama Na'Ama Na'ama al pi tnu'at Al Pi Tnu'At Al Pi Tnu'at Is there an easy way to get what I want? Should the current behaviour condidered a bug? My would be inclined to answer yes, but that may be because this behaviour would be wrong in Dutch. I'm not so sure about english. -- Antoon Pardon From ak at silmarill.org Thu Nov 2 16:18:59 2006 From: ak at silmarill.org (Rainy) Date: 2 Nov 2006 13:18:59 -0800 Subject: what's the difference between these two methods? (aka, why doesn't one of them work?) In-Reply-To: <1162501702.150119.313860@f16g2000cwb.googlegroups.com> References: <1162499293.080529.5480@m73g2000cwd.googlegroups.com> <1162500604.198685.97710@i42g2000cwa.googlegroups.com> <1162501702.150119.313860@f16g2000cwb.googlegroups.com> Message-ID: <1162502339.755106.126640@e3g2000cwe.googlegroups.com> JohnJSal wrote: > JohnJSal wrote: > > Peter Otten wrote: > > > > > > > ...the above is not a 1-tuple, but an ordinary string. You forgot the > > > trailing comma: > > > > > > ('notes',) > > > > Right you are! Now it works! :) > > > > Thanks! > > Oh great, now I've moved on to another issue. It seems that the list > appending isn't working right. All that gets added to a list is the > last value, not everything. Am I doing something wrong with the append > method? Well, append method is for appending a value to a list. A single value. You can use extend method (iirc) to extend a list with another list. From mrosenstihl at macnews.de Thu Nov 30 12:39:16 2006 From: mrosenstihl at macnews.de (Markus Rosenstihl) Date: Thu, 30 Nov 2006 18:39:16 +0100 Subject: failure building python 2.5 on mac os x 10.3.9 References: Message-ID: On 2006-11-19 15:50:14 +0100, Thomas Ploch said: > Hello, > > I followed the instructions in the Mac/README file. > > I ran ./configure --enable-framework > > But when I try to build from source with gcc 4.0.2, following happens: > > > [snip] > libtool: can't locate file for: -lSystemStubs > libtool: file: -lSystemStubs is not an object file (not allowed in a > library) > make: *** [Python.framework/Versions/2.5/Python] Error 1 > > What does that mean? > > Thanks, > Thomas I had the same problem (why do you have gcc-4.0.2?). -lSystemStubs is in Tiger First of all, try to install the 10.4 SDK as it will keep you away of a lot of linking problems and such stuff. (yes, it will install on 10.3.9 and since then i had no compile problems, i found this as an answer in a post in the apple discussions) Then try to compile it again after you have deleted the python source tree (or "make clean"). If that is still not working you have to edit the Makefile from Python and remove the -lSystemStubs (i think both ways work, but i am not sure) Make sure you have either a patched readline 5.1 or better a readline 5.2. Otherwise you will get segmentation faults when you are using ipython. If it is still not working, Good luck! From no-spam at no-spam-no-spam.invalid Sun Nov 5 12:39:59 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sun, 05 Nov 2006 18:39:59 +0100 Subject: socket.error.__bases__ = (EnvironmentError,) ? Message-ID: I've often trouble catching IO errors in general. Now a frequent case everywhere in an app after I've added a defaultsockettimout. Is this a legal/right practice to change the Exception tree like this: socket.error.__bases__ = (EnvironmentError,) And is there a chance that in future there is a common base exception class (EnvironmentError or an new super class) for these kind of exceptions (socket, httplib, ftplib, ...) -robert From researchbase at gmail.com Sat Nov 18 13:22:07 2006 From: researchbase at gmail.com (krishnakant Mane) Date: Sat, 18 Nov 2006 23:52:07 +0530 Subject: please help me choose a proper gui library. In-Reply-To: <200611181807.33571.phil@riverbankcomputing.co.uk> References: <200611181807.33571.phil@riverbankcomputing.co.uk> Message-ID: On 18/11/06, Phil Thompson wrote: > You have to install Qt first. You only need to install the run-time elements > (ie. the DLLs) on the client's machine. Unless your application is licensed > under the GPL (and you are using the GPL version of Qt and PyQt) then there > are components of Qt that you must not install on the client's machine. Yes, the software is licensed under gpl. how do I determine what run-time elements I need to install on the clien'ts machine and what is supposed to be skipped? > The only binary installer provided is for the GPL version of PyQt. Qt has > separate installers. It's easy enough to use something like NSIS to create > your own installer for your application that includes everything that it > needs. that's exactly what I am planning, only need to figure out what all do I need to package apart from the application executable. by the way I will be using cx_freze for creating executables. so I hope I will not require to also ship the PYQT modules? > PyQt fully supports Python 2.5. but my problem is that I will only be able to use python 2.4, is that ok? the PYQT installer asks "you seam to have a version older than python25, would you still like to continue?" is it safe to do so? I did not find a gpl binary for PYQT that is made for python24. please give the URL if possible. > Google for the different ones and try them out. which is the best editor which I can consider simple, does auto indentation and has some kind of auto completion features? it is ok if I don't get a gui designer. > In addition to your application you need to distribute the Qt DLLs (and > plugins if you use them), the corresponding PyQt .pyd files and sip.pyd. If > you are using the GPL version of Qt then you may also need to consider the > MinGW DLLs. Finally you need to consider if you need to distribute Python > itself. > > You might like to look at tools like PyInstaller for creating single > executables. this is all confusing for me right now. can you please give me any links possible for having a binary qt installer that will also install dlls required by PYQT? and how will I be able to determine what dll files and what other components I will need to ship with my installer? thanks. Krishnakant. From mauriceling at acm.org Thu Nov 16 03:55:18 2006 From: mauriceling at acm.org (Maurice LING) Date: Thu, 16 Nov 2006 08:55:18 GMT Subject: Will GPL Java eat into Python marketshare? In-Reply-To: <_jT6h.7906$ig4.2956@newsread2.news.pas.earthlink.net> References: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> <455b978c$1@news.unimelb.edu.au> <_jT6h.7906$ig4.2956@newsread2.news.pas.earthlink.net> Message-ID: <455c2773$1@news.unimelb.edu.au> Dennis Lee Bieber wrote: > On Wed, 15 Nov 2006 22:41:19 GMT, Maurice LING > declaimed the following in comp.lang.python: > > >>I'm hoping for a more optimistic outcome that this may open a >>possibility for tigher interoperability between java programs and python >>programs. That is, run java class files or java codes natively on python >>VM. Is this still a blue sky dream? >> > > Most unlikely to happen... I don't really see anyone going to the > effort to change the javac back-end to target a totally different > runtime engine. I admit that it is very very unlikely. I guess it is just a wild dream of mine to run Java bytecodes and Python bytecodes on Python VM. I do have a wild vision that we can import java libraries (as jar files) into CPython. ML From sjmachin at lexicon.net Sun Nov 12 04:14:13 2006 From: sjmachin at lexicon.net (John Machin) Date: 12 Nov 2006 01:14:13 -0800 Subject: Decimal() instead of float? In-Reply-To: References: <1163294604.4675.4.camel@pepper> Message-ID: <1163322853.760315.51040@k70g2000cwa.googlegroups.com> Steven D'Aprano wrote: > On Sun, 12 Nov 2006 02:31:04 +0100, Fredrik Lundh wrote: > > >> For example, I have a ZIP code > >> database that can do some processing on its numbers, and the numbers are > >> stored as floating point values (exactly) but Python doesn't get them > >> right > > > > sounds odd. are you sure you don't mean "stored as strings containing > > decimal numbers" ? > > > > (who uses fractional ZIP codes, btw?) > > Well, I can't speak for Americans, but here in Australia we typically give > our post codes to six decimal places: > > Melbourne 3000.000000 > Brunswick 3056.000000 > Clifton Hill 3068.000000 > Sydney 2000.000000 > St Johns Park 2176.000000 > > and so forth. You can't have too much precision with those floating point > post/ZIP codes! Here in Austraila, (I expect this is common to most countries), there are people who are utterly clueless about elementary data model rules, like identification "numbers" should be kept as strings. E.g. (1) National grief started over twenty years ago when the Post Office started using postcodes with leading zeroes, and continues to the present. The postcode for Darwin can be stored as 800, "800", or "0800". E.g. (2) Many Australians have a Tax File Number (TFN) which is a 9-digit number with an "officially kept secret" check digit algorithm (you need to sign an NDA with the Tax Office). Storing this as an integer allows the TFN be negative -- if the data entry for say 123456789 is actually 123456789-, you don't check for anything (length, allowable characters, check digit) and an old-fashioned trailing-minus-allowed conversion-to-integer routine is used. Cheers, John From fredrik at pythonware.com Mon Nov 27 04:50:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 27 Nov 2006 10:50:33 +0100 Subject: Inheritance from builtin list and override of methods. In-Reply-To: <200611271133.48359.mgiann@beta-cae.gr> References: <200611261804.54669.mgiann@beta-cae.gr> <200611271133.48359.mgiann@beta-cae.gr> Message-ID: Michalis Giannakidis wrote: >> in general, methods on C objects are implemented in terms of operations >> on the internal data structures, not in terms of a subset of the methods >> already provided by the object. > > But what is the reason that the assignment > l[2] = 6 > call my function, but > l.append(3) "obj[index] = value" maps to "obj.__setitem__(index, value)". reading the documentation might help; start here: http://docs.python.org/ref/specialnames.html From uche.ogbuji at gmail.com Sat Nov 18 02:44:51 2006 From: uche.ogbuji at gmail.com (Uche Ogbuji) Date: 17 Nov 2006 23:44:51 -0800 Subject: newbie: minidom In-Reply-To: <4555F394.80802@redlinepy.com> References: <4555F394.80802@redlinepy.com> Message-ID: <1163835891.744530.320360@j44g2000cwa.googlegroups.com> Paul Watson wrote: > Explicit [XML declaration] is better than implicit. Yes indeed. "Always use an XML declaration" http://www-128.ibm.com/developerworks/xml/library/x-tipdecl.html -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From mensanator at aol.com Fri Nov 17 12:48:24 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 17 Nov 2006 09:48:24 -0800 Subject: determining the bounds of a tuple returned from a database References: <1163743636.125450.98410@b28g2000cwb.googlegroups.com> <1163744646.708954.271010@f16g2000cwb.googlegroups.com> <1163746899.262327.72100@h48g2000cwc.googlegroups.com> Message-ID: <1163785704.361588.113640@m73g2000cwd.googlegroups.com> ronrsr wrote: > very sorry, that was my error - len(result[0]) and len(result[1]) both > return 1 -- > > i think I'm misunderstanding what len() does - to me they appear to > have 2 or 3 elements, or at least be composed of a string of some > length. One string composed of multiple data elements means the problem is in your database design, not in your Python code. > > I guess len() isn't the function i'm looking for then. How do I tell > how many strings, or how many bytes are in each dimension? You have to split the strings based on some delimiter, but your delimiters seem inconsistent. Unless the different delimiters actually have different meanings which, again, implies bad database design. > so that I > can iterate through them. > > Each entry in that list is a keyword - Alternately, is there any fast > way to parse that into a sorted list of distinct keywords. That could easily be done in the database itself, but only if it is designed properly. > > very sorry for the error. > > bests, > > -rsr- > > Fredrik Lundh wrote: > > ronrsr wrote: > > > > > it looks like the len() function is the one I want. > > > > > > for: len(result) - i get 248, > > > > > > but for len(result[0]) or len(result[1]) i always get 0. > > > > that's a bit surprising, because both items are tuples that contain > > exactly one item: > > > > >> (('Agricultural subsidies; Foreign aid',), ('Agriculture; Sustainable > > >> Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood > > >> Development, Birth Defects; Toxic Chemicals',), > > > > From Bulkan at gmail.com Wed Nov 8 01:18:52 2006 From: Bulkan at gmail.com (placid) Date: 7 Nov 2006 22:18:52 -0800 Subject: Python memory usage In-Reply-To: References: <1162964551.328495.211090@f16g2000cwb.googlegroups.com> Message-ID: <1162966732.195837.83280@i42g2000cwa.googlegroups.com> William Heymann wrote: > On Tuesday 07 November 2006 22:42, placid wrote: > > Hi All, > > > > Just wondering when i run the following code; > > > > for i in range(1000000): > > print i > > > > the memory usage of Python spikes and when the range(..) block finishes > > execution the memory usage does not drop down. Is there a way of > > freeing this memory that range(..) allocated? > > > > I found this document but the fix seems too complicated. > > > > http://www.python.org/pycon/2005/papers/79/python-memory.pdf > > > > Cheers > > Change range to xrange. It will run faster and use up almost no memory by > comparison. I know the point you are getting at for releasing memory however > in this case there is no reason to allocate the memory to begin with. Thanks for that it has fixed some of the memory problems. Just wondering if i continuously create different BeautifulSoup objects within a xrange() block when does the memory get released for this object, after the xrange() block, the next iteration of the xrange() block ? Cheers From grahamjfeeley at optusnet.com.au Sat Nov 4 17:09:52 2006 From: grahamjfeeley at optusnet.com.au (Graham Feeley) Date: Sun, 5 Nov 2006 08:09:52 +1000 Subject: WebScraping Message-ID: <454d0fb1$0$11970$afc38c87@news.optusnet.com.au> Can someone steer me to scripts / modules etc on webscraping please??? Ultimately I would like someone to write a script for me. However i am still searching for documentation on this subject Thanks Graham From ptmcg at austin.rr._bogus_.com Sat Nov 4 15:04:50 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 04 Nov 2006 20:04:50 GMT Subject: elementtree terminology + tangential questions References: <1162655068.276394.287080@m73g2000cwd.googlegroups.com> Message-ID: wrote in message news:1162655068.276394.287080 at m73g2000cwd.googlegroups.com... > 2) None of the xml documents to which I've had exposure (a very, very > small set) have had text between an element's end tag and the next tag, Text elements are not limited to printed/visible text. If you parsed a formatted XML string, I think the indenting whitespace shows up as text elements between tags. -- Paul From steve at holdenweb.com Thu Nov 2 10:22:33 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Nov 2006 15:22:33 +0000 Subject: is mod_python borked? In-Reply-To: <1162480110.992783.267620@e3g2000cwe.googlegroups.com> References: <1162480110.992783.267620@e3g2000cwe.googlegroups.com> Message-ID: walterbyrd wrote: > I am considering python, instead of php, for web-application > development. I often see mod_python.criticisized as being borked, > broken, or just plain sucking. > > Any truth to any of that? > Why don't you ask the very active mod_python mailing list that? Like all systems mod_python has its limitations, but it has an active development community who are extremely responsive to user and developer input. Follow-ups set to gmane.comp.python.mod_python. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From sjmachin at lexicon.net Thu Nov 9 20:27:37 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Nov 2006 17:27:37 -0800 Subject: pack a three byte int In-Reply-To: <1163120580.762226.22160@k70g2000cwa.googlegroups.com> References: <1163027401.386603.263030@k70g2000cwa.googlegroups.com> <1163092047.577688.140400@m73g2000cwd.googlegroups.com> <1163114202.636000.234900@m73g2000cwd.googlegroups.com> <1163115840.190634.5800@m73g2000cwd.googlegroups.com> <1163120580.762226.22160@k70g2000cwa.googlegroups.com> Message-ID: <1163122057.161515.70390@i42g2000cwa.googlegroups.com> p.lavarre at ieee.org wrote: > > Pack ' these things. > > The people who wrote this stuff forty years ago were thinking of bit > fields - here bit lengths of 8 then 3 then 21 then 8 then 8 bits - > cheating only when the bit boundaries happened to hit byte boundaries. > > Yes, as you describe in this example, I could cheat when the boundaries > happen to hit H or I boundaries as well, but then I'm still left coping > with the cases where the fields split on byte boundaries that are not H > or I boundaries, such as the example: > > Am I helping? Yes, you have *finally* said unambiguously what your problem really is -- field lengths not a multiple of 8 bits. I suggest that you start a new thread, write it out logically and ask for assistance. You should get some sensible answers. I will apologise in advance for not participating; I'm exhausted. Cheers, John From pavlovevidence at gmail.com Mon Nov 27 15:25:43 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 27 Nov 2006 12:25:43 -0800 Subject: super() and type() In-Reply-To: References: Message-ID: <1164659143.759204.127440@l12g2000cwl.googlegroups.com> Chris Mellon wrote: > I see super documented, and in use, as below (from the Python documentation) > > class C(B): > def meth(self, arg): > super(C, self).meth(arg) > > I'd like to not write C all the time, so is there any problem with writing: > > class C(B): > def meth(self, arg): > super(type(self), self).meth(arg) > > > This seems to work in practice but I don't see it used anywhere and > I'm worried what I might be missing. > > This was especially brought to my attention because pylint flags the > second usage as invalid, and I'm not sure if it should be considered a > false positive or not. PyLint is right. Try running this: class A(object): def meth(self,arg): print "hello" class B(A): def meth(self,arg): super(type(self), self).meth(arg) class C(B): def meth(self,arg): super(type(self), self).meth(arg) print C().meth(1) The reason this type(self) returns the type of the object (which doesn't change), NOT the type of the class it was defined in. That is, type(self) returns C even in the function B.meth. Since C's superclass is B, B.meth ends up calling B.meth again, and you get infinite recursion. Unfortunately, short of hackery, you're stuck with having to write out super(C,self). Carl Banks From peter.maas at somewhere.com Sat Nov 11 16:39:37 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 11 Nov 2006 22:39:37 +0100 Subject: explicit self revisited Message-ID: The Python FAQ 1.4.5 gives 3 reasons for explicit self (condensed version): 1. Instance variables can be easily distinguished from local variables. 2. A method from a particular class can be called as baseclass.methodname(self, ). 3. No need for declarations to disambiguate assignments to local/instance variables. All these reasons are valid and retained by the following suggestion: let self be represented by the dot, e.g. replace class someTest(unittest.TestCase): def setUp(self): self.ly = yList() self.m1 = self.ly[0].message self.m2 = self.ly[1].message self.m3 = self.ly[2].message def testList(self): self.assertEqual(len(self.ly),3) self.assertEqual(self.m1),"Ho") self.assertEqual(self.m2),"HoHo") self.assertEqual(self.m3),"HoHoHo") by class x(unittest.TestCase): def .setUp(): .ly = yList() .m1 = .ly[0].message .m2 = .ly[1].message .m3 = .ly[2].message def .testList(): .assertEqual(len(.ly),3) .assertEqual(.m1),"Ho") .assertEqual(.m2),"HoHo") .assertEqual(.m3),"HoHoHo") Methods could still be referenced e.g. as x.testList(someInstance). The current self syntax could still be valid (for backward compatibility.) Advantages of the new syntax: 1. Enhanced readability, less verbosity 2. Unambiguous: no need to tell newbies that a virtuous pythoneer has to stick to self instead of abbreviate it as s. 3. One argument less for "Python OO bolted on" propaganda. The second reason is the most important for me. I consider syntax control by a code of conduct as lame. The "leading dot" syntax could have further advantages: class x(object): a = "" # static variable .b = 0 # instance variable This could replace parameterless __init__ methods. Methods without leading dots could be considered static without a staticmethod decorator. For backward compatibility this behaviour should be explicitly activated e.g. by __autostatic__ = true. What do you think? -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From joshbloom at gmail.com Tue Nov 14 13:52:29 2006 From: joshbloom at gmail.com (Josh Bloom) Date: Tue, 14 Nov 2006 11:52:29 -0700 Subject: Looking for a way to stop execution of script, in the script In-Reply-To: References: Message-ID: Thanks Fredrik, yeah the while loop for single run is pretty stupid. sys.exit() thats the call I was looking for. -Josh On 11/14/06, Fredrik Lundh wrote: > > Josh Bloom wrote: > > > Hi everyone, I'm looking for a way to stop execution of a script from > > within the script. > > > > I'm familiar with this idiom: > > > > While 1: > > doFirstThing() > > doSecondThing() > > if something: > > break > > doThirdThing() > > break > > I'm not. why are you using a while statement to execute the code once? > > > doFirstThing() > > doSecondThing() > > if something: > > die > > doThirdThing() > > sys.exit() ? > > (or if you prefer, "raise SystemExit") > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Tue Nov 14 11:14:03 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 14 Nov 2006 18:14:03 +0200 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <8c7f10c60611130605i382312c4l829d6167ae0a5828@mail.gmail.com> <1163517440.042628.219590@h48g2000cwc.googlegroups.com> Message-ID: <000201c70876$fc746c80$03000080@hendrik> "Dan Lenski" wrote: > I think part of learning to think like a computer is learning to stop > associating computer logic too strongly with the natural language > meanings of "and", "or", and "not". This is true - and you have left out "but".... - Hendrik From jseigh_01 at xemaps.com Tue Nov 7 12:04:03 2006 From: jseigh_01 at xemaps.com (Joe Seigh) Date: Tue, 07 Nov 2006 12:04:03 -0500 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <1162913881.953664.254960@m73g2000cwd.googlegroups.com> References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <7xk62ct5pf.fsf@ruckus.brouhaha.com> <1162913881.953664.254960@m73g2000cwd.googlegroups.com> Message-ID: Ross Ridge wrote: > Joe Seigh wrote: > >>Basically there's a race condition where an object containing the >>refcount can be deleted between the time you load a pointer to >>the object and the time you increment what used to be a refcount >>and is possibly something else but definitely undefined. > > > That doesn't really make sense. The object can't be deleted because > the thread should already have a reference (directly or indirectly) to > the object, otherwise any access to it can cause the race condition you > describe. > True but if the thread didn't already have a reference, how would you get that initial reference to a shared object without a lock? -- Joe Seigh When you get lemons, you make lemonade. When you get hardware, you make software. From pavlovevidence at gmail.com Wed Nov 29 10:48:13 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 29 Nov 2006 07:48:13 -0800 Subject: Detecting recursion loops In-Reply-To: References: Message-ID: <1164815293.529674.109850@l39g2000cwd.googlegroups.com> robert wrote: > My code does recursion loops through a couple of functions. Due to problematic I/O input this leads sometimes to "endless" recursions and after expensive I/O to the Python recursion exception. > What would be a good method to detect recursion loops and stop it by user-Exception (after N passes or some complex criteria) without passing a recursion counter parameter through all the funcs? 1. You could catch RuntimeError at the top, check whether it's recursion depth exception, and raise a user exception if it is. 2. Consider whether you're unwittingly trying to cover up a bug. ISTM no matter how problematic the input is, you should at least be able to make progress on it. Are you getting this error because, say, you're not incrementing a counter somewhere, and thus recalling a function with the same arguments again? 3. Also consider whether you could rewrite the code to be non-recursive. Usually when I process input recursively, the input is allowed to be arbitrarily deeply nested. (In that case I think it would be a mistake to arbitrarily limit depth.) But it sounds to me like your input might be inherently non-nestable. If that's the case, it might be possible to get rid of the recursion altogether, or at least to put in error checking that detects when input is at an invalid depth. 4. If those concerns don't apply, and you do need to detect recursion, I'd suggest using a global dictionary to track function calls. If you have a function parse_something that you want to track, you could define a dict like this: _call_count = { parse_something: 0 } And change parse_something to adjust its own counter: def parse_something(): _call_count[parse_something] += 1 check_invalid_recursion() .... _call_count[parse_something] -= 1 (You could define a decorator to do this more easily; that's left as an excercise.) The check_invalid_recursion() function would inspect _call_count and raise an exception based on any criteria you want. 5. In CPython, you could just inpect the stack frame and look for duplicated function calls. See the documentation for sys._getframe. Carl Banks From martin at v.loewis.de Sat Nov 4 22:20:29 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 05 Nov 2006 04:20:29 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <7xpsc33zmh.fsf@ruckus.brouhaha.com> References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <454bd36c$0$2364$9b622d9e@news.freenet.de> <454ca6b4$0$151$9b622d9e@news.freenet.de> <7xpsc33zmh.fsf@ruckus.brouhaha.com> Message-ID: <454d587d$0$4361$9b622d9e@news.freenet.de> Paul Rubin schrieb: > "Martin v. L?wis" writes: >>> PS: Besides: what are speed costs of LOCK INC ? >> That very much depends on the implementation. In >> http://gcc.gnu.org/ml/java/2001-03/msg00132.html >> Hans Boehm claims it's 15 cycles. > > I think that has to be on a single processor, or at most a dual core > processor with shared cache on die. With multiple cpu chips I don't > think can get the signals around that fast. Can you explain what you mean? The lock# signal takes *immediate* effect, within the CPU cycle in which it is asserted. There is no delay whatsoever (except for speed-of-light issues, of course). Regards, Martin From mail at microcorp.co.za Thu Nov 2 04:16:59 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 2 Nov 2006 11:16:59 +0200 Subject: Tkinter Listbox string formatting question - how to kill a dancingsnake ? References: <02a901c6fcbf$181c51a0$03000080@hendrik> Message-ID: <024301c6fe5f$dca6b960$03000080@hendrik> "Fredrik Lundh" wrote: In the meantime, I have produced this evil hack, that takes advantage of the difference in pixel widths between the space, and either the fullstop or the single quote... It will only work if you have quite a lot of space to waste between columns, and I have only tested it for two sizes of Lucida and Helvetica - and for a fixed font like courier it seems to do no harm other than the cpu time it wastes... If the difference in width is one pixel, it lines up the next thing to be added to the string exactly, else it almost gets it right... I find the few (up to one less than there are pixels in a space) characters it adds into the line less visually disturbing than the dancing snake column caused by the full space width variation. anyway for what its worth, here it is: # this does some text padding to try to line variable font stuff up def pad_text(txt,pixlen,fontp): """This does padding up to a pixel value exploiting differences between space, fullstop or single quote widths. txt is a text string pixlen is an int - the number of pixels to "tab" to fontp is the font parameter """ a = fontp.measure(txt) diff = pixlen - a if diff < 0: return "string too long too fit in pixels" spsize = fontp.measure(' ') fssize = fontp.measure('.') sqsize = fontp.measure("'") repchr = ' ' rpsize = spsize numr = 0 rpdiff = 0 if spsize != fssize: repchr = '.' rpsize = fssize rpdiff = abs(fssize - spsize) elif spsize != sqsize: repchr = "'" rpsize = sqsize rpdiff = abs(spsize - sqsize) numspace, rem = divmod(diff,spsize) if rem == 0: numr = 0 else: if spsize < rpsize: numspace -= rem/rpdiff numr = rem/rpdiff elif spsize > rpsize: numr = (spsize - rem)/rpdiff numspace = numspace - numr + 1 numspace -= 2 txt = txt + ' ' while numr > 0: txt = txt + repchr numr -= 1 while numspace > 0: txt = txt + ' ' numspace -= 1 return txt Feel free to play the critic... - Hendrik From deets at nospam.web.de Sun Nov 12 11:26:08 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 12 Nov 2006 17:26:08 +0100 Subject: writing wx code in emacs - how to make easier? In-Reply-To: References: Message-ID: <4rp08uFs2el7U1@mid.uni-berlin.de> > I would like to write wx code in emacs. For now I'm using python-mode > but I hope they are stuff which make it easier. I mean some > autocompletion or abbrevs of such things as wx.ALIGN* wx.EVT_* ... Create a TAGS-file using e.g. find -type f | xargs -L1 etags --append Then use the emacs completion-feature M-/ Diez From dynamicdestroyer at yahoo.de Wed Nov 15 12:39:28 2006 From: dynamicdestroyer at yahoo.de (Mateuszk87) Date: 15 Nov 2006 09:39:28 -0800 Subject: Yield In-Reply-To: References: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> Message-ID: <1163612368.317372.232420@b28g2000cwb.googlegroups.com> thx for the quick answer. i ll have a look. From tjreedy at udel.edu Fri Nov 17 21:58:21 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 17 Nov 2006 21:58:21 -0500 Subject: How can I speed this function up? References: Message-ID: "Chris" wrote in message news:kou7h.67901$rP1.39303 at news-server.bigpond.net.au... > def write_data1(out, data): > for i in data: > if i[0] is 'ELEMENT': Testing for equality with 'is' is a bit of a cheat since it is implementation dependent, but since you have a somewhat unfair constraint .... > out.write("%s %06d " % (i[0], i[1])) Since i[0] is tested to be "ELEMENT', this should be the same as out.write("ELEMENT %06d " % i[1]) which saves constructing a tuple as well as an interpolation. > for j in i[2]: > out.write("%d " % (j)) > out.write("\n") tjr From zzf818 at gmail.com Tue Nov 7 21:14:01 2006 From: zzf818 at gmail.com (kelin,zzf818@gmail.com) Date: 7 Nov 2006 18:14:01 -0800 Subject: __init__ function problem References: <1162905967.354604.38230@k70g2000cwa.googlegroups.com> <1162929803.735097.279460@i42g2000cwa.googlegroups.com> <1162946870.504386.302530@m7g2000cwm.googlegroups.com> Message-ID: <1162952041.142178.158500@h54g2000cwb.googlegroups.com> Hi, I've read all of this. And I am clear about it. Thanks all. Best Regards! Gabriel Genellina wrote: > At Tuesday 7/11/2006 21:47, Jia Lu wrote: > > > > In Python, the real constructor is called __new__, > > > > Carl Banks > > > >But the code below won't invoke __new__: > > Is this a question, or just for making things more and more confusing > to beginners? > > >class Test: > > def __new__(self, value): > > print "__new__",value > > For old-style classes __new__ is not used. On new-style classes it's > used mostly for dealing with immutable objects. The code should be: > > class NewStyle(object): > "A new style class inherits from object in some way" > def __new__(cls, value): > print "NewStyle.__new__",value > return super(NewStyle, cls).__new__(cls, value) > # return object.__new__(cls, value) for lazy people > > def __init__(self, value): > print "NewStyle.__init__",value > > class OldStyle: > "An old style class does not inherit from object" > def __init__(self, value): > print "OldStyle.__init__",value > > n = NewStyle(1) > o = OldStyle(2) > > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! > ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From bignose+hates-spam at benfinney.id.au Wed Nov 8 20:27:12 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 09 Nov 2006 12:27:12 +1100 Subject: assigning values in __init__ References: <454faf57$0$12993$c3e8da3@news.astraweb.com> <4550daa6$0$26446$c3e8da3@news.astraweb.com> <4551fe01$0$7047$c3e8da3@news.astraweb.com> Message-ID: <877iy5mmtr.fsf@benfinney.id.au> John Salerno writes: > Ben Finney wrote: > > If you pass a *mapping* of the > > "I-might-want-to-add-more-in-the-future" values, then you get both > > explicit *and* expandable, without an arbitrary unneeded sequence. > > Do you mean by using the **kwargs parameter? No. I mean what I said in this earlier post on this thread: If you have a group of named, semantically-related, unsequenced values, pass them into the function as a mapping object (a dict object). -- \ "I have yet to see any problem, however complicated, which, | `\ when you looked at it in the right way, did not become still | _o__) more complicated." -- Paul Anderson | Ben Finney From sjmachin at lexicon.net Thu Nov 9 21:09:37 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Nov 2006 18:09:37 -0800 Subject: how is python not the same as java? In-Reply-To: References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> Message-ID: <1163124577.908610.122310@e3g2000cwe.googlegroups.com> Jorge Vargas wrote: > On 9 Nov 2006 16:44:40 -0800, gavino wrote: > > both are interpreted oo langauges...... > > > that is not correct java is compiled and the VM interprets the code ... and what do you think is in those pesky little .pyc files you may have noticed lying around on your hard disk? From __peter__ at web.de Sun Nov 5 08:02:36 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 05 Nov 2006 14:02:36 +0100 Subject: Is there a commas-in-between idiom? References: Message-ID: Ernesto Garc?a Garc?a wrote: > it's very common that I have a list and I want to print it with commas > in between. How do I do this in an easy manner, whithout having the > annoying comma in the end? >>> items = [1, 2, 3, "many"] >>> print ", ".join(str(item) for item in items) 1, 2, 3, many Peter From manelitoau at gmail.com Wed Nov 8 08:29:49 2006 From: manelitoau at gmail.com (manelitoau at gmail.com) Date: 8 Nov 2006 05:29:49 -0800 Subject: Python Jogos Message-ID: <1162992589.682760.282340@k70g2000cwa.googlegroups.com> Jogo da velha Jogo do galo Codigos em python kem me arranja From ghidox at gmail.com Wed Nov 22 17:14:30 2006 From: ghidox at gmail.com (Ghido) Date: 22 Nov 2006 14:14:30 -0800 Subject: Global object Message-ID: <1164233669.952808.148210@j44g2000cwa.googlegroups.com> Hi all, i need to save in an object some variable for use in other parts of my software. it's possibile without create an istance of this class in every file? if yes how? thanks a lot Ghido From lorenzo at excitement.com Sat Nov 4 15:58:29 2006 From: lorenzo at excitement.com (Lorenzo) Date: Sat, 04 Nov 2006 14:58:29 -0600 Subject: NEWBIE: Script help needed Message-ID: I have this script that I want to use weekly to send me email with information regarding disk space and available upgrades for my system. This script is actually a learning tool for me as I learn Python. The problem I've run into has me stumped and I need some help. What happens is when the script runs it does these things, parses the result and appends that to an html string: 1) checks disk space by using df -t reiserfs 2) runs time emerge --sync 3) runs emerge -uvp world 4) runs emerge -uv --fetchonly world The 'emerge' command is a Gentoo specific one. If I remove step 3), everything else runs just fine, the email is sent and I receive what I expect. But when step 3) is allowed to run, even if its the only command that runs, it hangs somewhere in the function getCommandOutput. If I try and debug the command, it appears to hang on this line: err = child.wait() I suspect a race condition, but I'm not sure how to proceed, can someone lend me a hand. Here is the script I wrote, I got the command getCommandOutput from this site: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52296 TIA [code] #!/usr/bin/python ################################ ### NEED TO RUN THIS AS ROOT ### ### EMERGE SYNC REQUIRES THIS ### ################################ import os, re, smtplib, MimeWriter, mimetools, cStringIO, popen2, fcntl, select, pdb cmd = 'df -t reiserfs' finalList = [] theOutput = [] text = "This realy should be in HTML" html = "\ \ \ \
Disk Utilization on Hedley:
" out = cStringIO.StringIO() writer = MimeWriter.MimeWriter(out) txtin = cStringIO.StringIO(text) def createhtmlmail (html, text, subject): """Create a mime-message that will render HTML in popular MUAs, text in better ones""" import MimeWriter import mimetools import cStringIO out = cStringIO.StringIO() # output buffer for our message htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) # # set up some basic headers... we put subject here # because smtplib.sendmail expects it to be in the # message body # writer.addheader("Subject", subject) writer.addheader("MIME-Version", "1.0") writer.addheader("From", "Hedley at myserver.com") writer.addheader("To", "lorenzo at myserver.com") # # start the multipart section of the message # multipart/alternative seems to work better # on some MUAs than multipart/mixed # writer.startmultipartbody("alternative") writer.flushheaders() # # the plain text section # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() # # start the html subpart of the message # subpart = writer.nextpart() subpart.addheader("Content-Transfer-Encoding", "quoted-printable") # # returns us a file-ish object we can write to # pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() # # Now that we're done, close our writer and # return the message body # writer.lastpart() msg = out.getvalue() out.close() print msg return msg def makeNonBlocking(fd): fl = fcntl.fcntl(fd, fcntl.F_GETFL) try: fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY) except AttributeError: fcntl.fcntl(fd, fcntl.F_SETFL, fl | fcntl.FNDELAY) def getCommandOutput(command): theOutput = [] child = popen2.Popen3(command, 1) # capture stdout and stderr from command child.tochild.close() # don't need to talk to child outfile = child.fromchild outfd = outfile.fileno() errfile = child.childerr errfd = errfile.fileno() makeNonBlocking(outfd) # don't deadlock! makeNonBlocking(errfd) outdata = errdata = '' outeof = erreof = 0 while 1: ready = select.select([outfd,errfd],[],[]) # wait for input if outfd in ready[0]: outchunk = outfile.read() if outchunk == '': outeof = 1 outdata = outdata + outchunk if errfd in ready[0]: errchunk = errfile.read() if errchunk == '': erreof = 1 errdata = errdata + errchunk if outeof and erreof: break select.select([],[],[],.1) # give a little time for buffers to fill err = child.wait() if err != 0: raise RuntimeError, '%s failed w/ exit code %d\n%s' % (command, err, errdata) theOutput.append(outdata) theOutput.append(errdata) return theOutput #Run df and get the disk info output = os.popen(cmd) # match two or more spaces, the header line has a sngle # space between the 'Mouted on' field # We need to keep those together # The other spaces are the separation in the field headers # To get the output from df down to just the field headers # and the data, we need to match 2 or more spaces # -1 eliminates the \n at the end of output. # We'll get it back when we write each line to the # mail message, I suspect html += "" for lines in output.readlines(): p = re.compile('\ +') formattedText = p.subn('??????', lines[:-1], 5) html += formattedText[0] + '
' html += "
" mydata = getCommandOutput("time emerge --sync") p = re.compile('\ +') p.subn('?', mydata[1])[0] p = re.compile('\n') string = (p.subn('
', mydata[1]))[0] html += "

Sync Time: " + "
" + "
" + "" + string + "" mydata = "" mydata = getCommandOutput("emerge -uvp world") p = re.compile('\ +') (p.subn('?', mydata[0]))[0] p = re.compile('\n') html += "" + (p.subn('
', mydata[0]))[0] + "
" try: getCommandOutput('emerge -uv --fetchonly world') html += "
Fetch completed successfuly!
" except RuntimeError: html += "< font color='Red'>
******Fetch did not complete successfully!*********" html+= ' ' out = cStringIO.StringIO() writer = MimeWriter.MimeWriter(out) txtin = cStringIO.StringIO("This should be in HTML") subject = "Emerge info and disk utilization on Hedley" message = createhtmlmail(html, text, subject) server = smtplib.SMTP("hedley") server.sendmail('Hedley at myserver.com', 'lorenzo at myserver.com', message) server.quit() [/code] -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty From ralmeida at gmail.com Thu Nov 23 07:32:54 2006 From: ralmeida at gmail.com (Rob De Almeida) Date: 23 Nov 2006 04:32:54 -0800 Subject: WSGI with mod_python (was: Python, WSGI, legacy web application) References: <1164241791.372210.103330@b28g2000cwb.googlegroups.com> Message-ID: <1164285174.400852.237700@j44g2000cwa.googlegroups.com> Ben Finney wrote: > I was under the impression that WSGI in mod_python was a rather kludgy > way to do WSGI, but I don't know what the alternatives are. CGI? > Python http server (e.g. CherryPy)? Something else? You can use FastCGI or SCGI too, with Apache, lighttpd or Cherokee. I have a short description of different ways to run a WSGI app here: http://pydap.org/docs/server.html Though it's focused on a specific WSGI app I wrote it uses Paste Deploy, so you can generalize it easily. --Rob From anthra.norell at vtxmail.ch Thu Nov 2 14:59:25 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Thu, 02 Nov 2006 20:59:25 +0100 Subject: SE 2.3 temporarily unavailable. Cheese shop defeats upload with erratic behavior. Urgently requesting help. In-Reply-To: <200611021020.31599.inq1ltd@verizon.net> References: <4549FA01.4090706@vtxmail.ch> <200611021020.31599.inq1ltd@verizon.net> Message-ID: <454A4E1D.8030106@vtxmail.ch> jim-on-linux wrote: > Frederic, > > I've been trying to get back into my package in > the Cheese Shop for over a year. The phone > company changed my e:mail address and to make a > long and frustrating story short I can't get back > into the Cheese Shop to make changes to my file. > > Time is money. At some time you have to consider > if it is worth it. At least you have the name of > your program listed. > > I wish I could be more helpfull. I'll watch the > responses you get from others. > > Good Luck, > jim-on-linux > > http://www.inqvista.com > > > > > > > On Thursday 02 November 2006 09:00, you wrote: > >> Some time ago I had managed to upload a small >> package to the Cheese Shop using the data entry >> template. Uploading is in two steps: first the >> text then the package file. When I had a new >> version it went like this: The new text made a >> new page, but the new file went to the old >> > snip > Thanks for letting me know that I am not alone. Do you know of an alternative to the Cheese Shop? Frederic From steve at REMOVE.THIS.cybersource.com.au Fri Nov 10 21:06:06 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 11 Nov 2006 13:06:06 +1100 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> Message-ID: On Fri, 10 Nov 2006 13:16:32 -0600, Michael Hobbs wrote: > Yeah, okay, I didn't read through the details of the PEP. I picked a bad > example to illustrate a point that is still true. The FAQ also tries to > argue that it's a Good Thing that join() is a string method, not a list > method. It also tries to argue that there's a good reason that lists are > different than tuples. I don't think it would surprising that many > Python developers don't really buy those arguments either. Well, as far as I'm concerned, you've just blown your credibility completely out the water now. Yes, I'm aware that there are many Python programmers who don't get join() or lists/tuples, but I'm constantly surprised by that fact. At the risk of starting another argument, to my mind that's like discovering that there are professional butchers who don't think that using a sharp knife is a good idea. -- Steven. From godson.g at gmail.com Fri Nov 24 01:40:33 2006 From: godson.g at gmail.com (Godson) Date: Fri, 24 Nov 2006 12:10:33 +0530 Subject: Porting Tkinter application to JYthon In-Reply-To: <20061123045218.BFAF8CA0A4@ws5-11.us4.outblaze.com> References: <20061123045218.BFAF8CA0A4@ws5-11.us4.outblaze.com> Message-ID: On 11/23/06, sandip desale wrote: > > Dear All, > > We have a Tcl/Tk application written using Python 2.2. Using this > application we want to call some customizable Java APIs. I tried porting > Tcl/Tk application to Jython but not able to do the same as TKinter library > is not available with JYthon. > > Can you please help me in porting Tkinter application to Jython? Also > kindly let me know how to do the same. > > > Thanks & Regards, > Sandip Desale > > > -- > > Search for products and services at: > http://search.mail.com > -- > http://mail.python.org/mailman/listinfo/python-list > Try this, may be this is what you are looking for http://jtkinter.sourceforge.net/ Godson Gera http://godson.auroinfo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From tiedon_jano at hotmail.com Sat Nov 11 17:50:34 2006 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sat, 11 Nov 2006 22:50:34 GMT Subject: How to choose the right GUI toolkit ? In-Reply-To: <1163277168.079436.65120@e3g2000cwe.googlegroups.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163015347.164393.74110@i42g2000cwa.googlegroups.com> <6ov7l2lb9ip2u5jmd54e2kso1s78fc68bb@4ax.com> <1163139352.206221.213180@m73g2000cwd.googlegroups.com> <1163141290.868726.11330@h48g2000cwc.googlegroups.com> <43hal2p6ep7vds2nl55uqil7v7i3guncl2@4ax.com> <1163277168.079436.65120@e3g2000cwe.googlegroups.com> Message-ID: <_ss5h.372$Nv3.369@read3.inet.fi> John Henry wrote: > BTW: I did a search and found the testnotebook example from: > > http://prdownloads.sourceforge.net/pythoncard/testNotebook.zip?download > > and tried it out. There is one error in the widget.py that I have to > get around. Changed from: > > canvas.setFillColor('gray') > > to: > > try: > canvas.setFillColor('gray') > except: > pass > > and then ran it. Works! > > So, yes, you can do Notebook in Python. I believe what they are saying > is that Notebook isn't supported fully (yet) in the resourceeditor. It's true that the notebook and grid components of wxPython are not completely integrated into PythonCard but they can still be used quite easily once you figure out how. The process of figuring out can be made easier by a working example. The real life application Blood Pressure Monitor http://personal.inet.fi/cool/operator/BPMDownload.html can be used as an example of using the notebook, grid and htmlwin widgets in PythonCard. I use this application to input the pressure values I've registered with my own meter and to produce a PDF page with PyChart to hand to my doctor to inspect when I visit him twice a year. Cheers, Jussi -- Jussi Salmela http://personal.inet.fi/cool/operator/ From john106henry at hotmail.com Fri Nov 17 16:42:47 2006 From: john106henry at hotmail.com (John Henry) Date: 17 Nov 2006 13:42:47 -0800 Subject: About alternatives to Matlab In-Reply-To: <1163792282.802768.216630@m73g2000cwd.googlegroups.com> References: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> <1163711343.870829.110030@h48g2000cwc.googlegroups.com> <1163713573.147702.229320@k70g2000cwa.googlegroups.com> <1163792282.802768.216630@m73g2000cwd.googlegroups.com> Message-ID: <1163799767.280869.247000@b28g2000cwb.googlegroups.com> Thanks for pointing that out. I wasn't aware of this. Will take a look. S?bastien Boisg?rault wrote: > On Nov 16, 10:46 pm, "John Henry" wrote: > > Bill Gates will have you jailed! :-) > > > > On a more serious note, is there any alternative to Simulink though? > > Ptolemy II. Java stuff in the core but components may be written in > Python > > http://ptolemy.eecs.berkeley.edu/ptolemyII/ > http://ptolemy.eecs.berkeley.edu/ptolemyii/ptII5.0/ptII/doc/codeDoc/ptolemy/actor/lib/python/PythonScript.htm > > > sturlamolden wrote: > > >and is infinitely > > > more expensive. > > > > > Does anyone wonder why I am not paying for Matlab maintenance anymore? > > > > > Sorry Mathworks, I have used your product for years, but you cannot > > > compete with NumPy. > > > > > Cheers, > > > Sturla Molden From torriem at chem.byu.edu Tue Nov 14 23:48:35 2006 From: torriem at chem.byu.edu (Michael Torrie) Date: Tue, 14 Nov 2006 21:48:35 -0700 Subject: Python v PHP: fair comparison? In-Reply-To: <1163559359.010787.185840@m73g2000cwd.googlegroups.com> References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> Message-ID: <1163566115.10270.5.camel@enterprise.local.lan> On Tue, 2006-11-14 at 18:55 -0800, Luis M. Gonz?lez wrote: > > > - Python is more readable, and more general purpose > > Yes, php is only for web. Absolutely false. Most of my standalone, command-line scripts for manipulating my unix users in LDAP are written in PHP, although we're rewriting them in python. Although I can't think of a single app written in php that's not web- based (other than standalone scripts I have written), there are up-to- date php bindings for GTK: http://gtk.php.net/ Michael > On the other hand, Python is a general purpose language and it can be > used for nearly anything you may want to do. > > > - PHP has awful backward compatibility > > Yes. And it's also an ugly language to work with. > > > - PHP has a lower barrier to entry > > I don't think it is any easier than python. Not even to begin with. > > > - Most inexpensive web-hosters support PHP, but not Python > > Sad but true. > > > - PHP has far more pre-writen scripts available > > For web projects, perhaps. > But I'm sure you can do everything better with python, especially with > the new crop of web frameworks (Django, Turbo Gears, etc...). > > > - Newer versions of mod_python require Apache 2.0, which few hosters > > have > > You can also get alder versions of mod_python. What's the problem? > > > - There is more demand for PHP developers, than Python developers > > So you want to be a web developer? > Then look no further. Learn python and go kick php developers asses in > the market place. > There are thousands of php developers out there. Do you want to be just > one more? > I'd rather learn something newer, and much more powerful. > And once you get a job, you will do everything better and faster than > the others, your quality will stand up from the rest and so your > reputation. > Then there will be more demand for "your skills". > From nick at craig-wood.com Tue Nov 28 05:30:09 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 28 Nov 2006 04:30:09 -0600 Subject: "fork and exit" needed? References: <8osmm21skionildtnme1j0nvqbla6oqk72@4ax.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > In <8osmm21skionildtnme1j0nvqbla6oqk72 at 4ax.com>, Vincent Delporte wrote: > > > Anyone knows if those lines are necessary, why, and what their > > alternative is in Python? > > > > open STDOUT, '>/dev/null'; > > sys.stdout = open(os.devnull, 'w') This doesn't have the desired effect If you run this import os,sys,time print os.getpid() sys.stdout = open(os.devnull, 'w') time.sleep(60) It prints its pid. $ ls -l /proc/32004/fd total 4 lrwx------ 1 ncw ncw 64 Nov 28 09:55 0 -> /dev/pts/17 lrwx------ 1 ncw ncw 64 Nov 28 09:55 1 -> /dev/pts/17 lrwx------ 1 ncw ncw 64 Nov 28 09:55 2 -> /dev/pts/17 l-wx------ 1 ncw ncw 64 Nov 28 09:55 3 -> /dev/null That quite clearly shows that stdout isn't /dev/null which is required for proper deamonisation under unix. I'm not sure how you do open stdout to /dev/null in python though! I suspect something like this... import posix posix.close(1) posix.open("/dev/null", posix.O_WRONLY) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From http Wed Nov 8 13:01:56 2006 From: http (Paul Rubin) Date: 08 Nov 2006 10:01:56 -0800 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? References: <1162947569.228388.16940@m7g2000cwm.googlegroups.com> Message-ID: <7xy7qlom0b.fsf@ruckus.brouhaha.com> robert writes: > what about speed. Is it true that IronPython is almost as fast as C-Python meanwhile? > > When this all is really true, its probably a proof that putting out > LOCK-INC-lock's (on dicts, lists, mutables ...) in CPython to remove > the GIL in future should not be really so expensive as it was teached > in the past :-) I don't think IronPython uses locks that way. AFAIK it doesn't use reference counts, and relies on user-supplied synchronization to keep stuff like dictionaries safe. From sjmachin at lexicon.net Tue Nov 28 21:26:29 2006 From: sjmachin at lexicon.net (John Machin) Date: 28 Nov 2006 18:26:29 -0800 Subject: Floating Exception References: Message-ID: <1164767189.395397.128450@l39g2000cwd.googlegroups.com> Jeremy wrote: > Hi, > > I just changed some previously-working Python program to add a C++ > extension. > > Now, when I call __init__() in a Python class I did not change and with the > same arguments passed, I get the screen message 'Floating exception' and the > program seems to stop. The exact point of the crash in __init__() seems to > depend on from which directory I run the Python program. > > What is wrong? Could it possible be your C++ extension, do you think? > And what is a floating exception? Do you know how to use Google? Search for "floating exception". Fix your extension, and it'll go away. HTH, John From aahz at pythoncraft.com Thu Nov 30 16:40:49 2006 From: aahz at pythoncraft.com (Aahz) Date: 30 Nov 2006 13:40:49 -0800 Subject: Python spam? References: Message-ID: In article , Thomas Heller wrote: >Aahz schrieb: >> >> Anyone else getting "Python-related" spam? So far, I've seen messages >> "from" Barry Warsaw and Skip Montanaro (although of course header >> analysis proves they didn't send it). > >I'm getting spam not only from Barry, but also from myself ;-) with >forged headers. But I'm not sure what you mean with Python-related... >Not the contents, IIRC. Thing is, I don't usually get spam "from" people I know (or at least it gets filtered before I see it), so someone is clearly using some resource of Python-related email addresses. Just seems rather odd, and I wonder whether it's some kind of DoS attack or what. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Member of the Groucho Marx Fan Club From _karlo_ at _mosor.net_ Thu Nov 2 12:02:28 2006 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Thu, 2 Nov 2006 17:02:28 +0000 (UTC) Subject: Forum written in Python? Message-ID: Are there any forum or bulletin board systems written entirely in Python? I got sick of PhpBB, mostly because I can't tweak and fiddle with the code, since I really don't like PHP and don't know it that well. I thought of writting my own simple forum software, but if there are existing projects out there, I wouldn't mind contributing. So far I found out about Pocoo, but it seems to immature right now, I was looking for something comparable to PhpBB or IPB? -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From steve at REMOVEME.cybersource.com.au Wed Nov 15 02:12:32 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 15 Nov 2006 18:12:32 +1100 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <17750.22816.636590.485360@montanaro.dyndns.org> <4558B9E3.2040207@hobbshouse.org> Message-ID: On Tue, 14 Nov 2006 12:01:05 +0000, Antoon Pardon wrote: > On 2006-11-13, Ben Finney wrote: >> Michael Hobbs writes: >> >>> To be clear, this is the actual thrust of my argument. It seems >>> redundant to have *both* line continuations and colons in compound >>> statements. >> >> Why are you trying to remove redundancy? > > Why not? My impression is that removing redundancy is considered > a positive thing here in c.p.l. Redundancy in *what*? Redundancy is not something to be valued for its own sake. It is only valuable when it actually gains you something. e.g. x + y and x.__add__(y) are redundant, BUT __add__ is necessary for operator overloading and + operator is necessary for readability and easy arithmetic expressions. Likewise, operator.add is useful for local optimizations, and so is to be valued despite the redundancy of yet another way to do addition. But a hypothetical built-in function add(x,y) => x+y would be redundant for no good reason, and therefore to be resisted. The question is not "is the colon redundant?" but "is the colon useful despite, or even because, its redundancy?". There are two schools of thought: (1) Yes, it is useful, *because* of its redundancy -- it helps the human reader parse and comprehend the source code. Evidence given: usability studies by the ABC project. (2) No, it is not useful, because the computer parser doesn't need it. Evidence given: "it seems to me" repeated loudly until our ears bleed. People's intuition is notoriously poor at judging usability. I don't say I give it zero credence, but I give it very little. -- Steven D'Aprano From john.smith at nowhere.com Sun Nov 26 19:31:39 2006 From: john.smith at nowhere.com (john.smith at nowhere.com) Date: Sun, 26 Nov 2006 19:31:39 -0500 Subject: test message Message-ID: <9fckm2p839oh7c586t93c9fn3lfppu43g3@4ax.com> This is a test message, please ignore. From john at castleamber.com Thu Nov 16 01:37:38 2006 From: john at castleamber.com (John Bokma) Date: 16 Nov 2006 06:37:38 GMT Subject: Will GPL Java eat into Python marketshare? References: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Seriously though, there is no contradiction between the idea of > "people use Python instead of Java because they prefer to avoid pain" It sounds like a typical fanboy statement to me, since it implies that Java is always a pain, and Python is perfect. I can't take such a statement nor the person writing it down serious at all. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From deets at nospam.web.de Thu Nov 9 17:54:49 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 09 Nov 2006 23:54:49 +0100 Subject: how to create a multicolor "font-string" in pygame?? In-Reply-To: <1163106732.026203.111360@m73g2000cwd.googlegroups.com> References: <1163106732.026203.111360@m73g2000cwd.googlegroups.com> Message-ID: <4rhptpFrneqhU1@mid.uni-berlin.de> Iacopo.Marmo at gmail.com schrieb: > Hi! I need to manipulate multicolor strings, i.e. strings with a color > associated with each letter. > Any suggestions? There is no support for multi-color strings as such in pygame. If you use a fixed-width font, things are easy. Just create the strings one after another using spaces as prefix. E.g. back = (0,0,0) font = pygame.font.Font(font_fn, size) images = [] for i, c in enumerate("colored string"): s = " " * i + c color = color_for_index(i) s_image = font.render(s, True, color, back) images.append(s_image) Then blit the images onto each other. If you don't use fixed widht fonts, things get more complicated. Then you should calculate the size of the prefix to a certain characer, and store that together with the image: text = "colored string" back = (0,0,0) font = pygame.font.Font(font_fn, size) images = [] for i, c in enumerate(text): s = " " * i + c color = color_for_index(i) prefix_offest = font.size(text[:i]) s_image = font.render(s, True, color, back) images.append((prefix_offset, s_image)) Then you have to combine the images according to the prefix offset. Diez From CRhode at LacusVeris.com Sat Nov 18 20:24:10 2006 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Sat, 18 Nov 2006 19:24:10 -0600 Subject: Finding skilled pythonistas for micro-jobs? In-Reply-To: <7x64dc8e24.fsf@ruckus.brouhaha.com> References: <1163895209.986877.13820@f16g2000cwb.googlegroups.com> <7x64dc8e24.fsf@ruckus.brouhaha.com> Message-ID: <20061119012410.GA12944@loki> Paul Rubin wrote this on Sat, Nov 18, 2006 at 04:39:47PM -0800. My reply is below. > "darran" writes: > > Any suggestions then for locating skilled Python/C++ programmers > > for these small (micro) jobs? > I've taken a number of these and always regretted it. They've been > far more hassle than they're worth. But maybe that's just me. I've never seen the point of trying to compete for the kind of work-at-home programming jobs you see posted on Internet clearing houses. A number of reservations have always stopped me: o The problem descriptions are nebulous or incoherent or both. o No background scope is provided. o No performance criteria are set forth. o No pay rate is specified. o No due date is mentioned. Obviously, it would take longer to draw these things together than it would to do the job itself, at least in the posters' opinions. I can't help wondering, though, if they're serious, because, if they need the job completed successfully, however trivial it may be, sooner or later somebody is going to have to do their homework, and, yes, it's going to take at least twice as long as they're willing to spend when they get around to it. I think there's a case to be made for hiring a another full-time programmer if these small jobs keep cropping up. Part of his job description can be to prepare needs assessments and impact analyses and to prioritize requests before he even thinks about beginning a task. It's difficult to outsource these things, and they are time consuming. -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 38? ? Wind NNW 9 mph ? Sky overcast. From scott.daniels at acm.org Mon Nov 6 23:24:55 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 06 Nov 2006 20:24:55 -0800 Subject: Projecting MUD maps In-Reply-To: <4r8qjtFpkllgU2@uni-berlin.de> References: <4r79c5Fptb28U1@uni-berlin.de> <4r8qjtFpkllgU2@uni-berlin.de> Message-ID: <455001b5$1@nntp0.pdx.net> Diez B. Roggisch wrote: > But there is no cookbook-algorithm that will produce perfect MUD-maps. For > such a beast, you have to cough up one on your own, with things like > constraint solvers and the like. Certainly over _my_ head, at least without > deep studies of planar graph representation problems. To convince yourself of this, here is a small problem that does not flatten to any simple 2-D solution. Consider : A, B, C a, b, c A.south, B.South, C.south = a, b, c a.north, b.north, c.north = A, B, C A.east, B.east, C.east = a, b, c a.west, b.west, c.west = A, B, C a.east, b.east, c.east = A, B, C A.west, B.west, C.west = a, b, c -- --Scott David Daniels scott.daniels at acm.org From infotechsys at pivot.net Sun Nov 19 10:36:42 2006 From: infotechsys at pivot.net (infotechsys at pivot.net) Date: Sun, 19 Nov 2006 10:36:42 -0500 Subject: A little confuse Message-ID: <1163950602.32026.9.camel@Tiredbones.lan> When I run this code in the pdb it works. accountNbr = 1 for testLine in ftest.readlines(): acct = testLine[1:2] #there account number if accountNbr == int(acct): accountNbr = accountNbr + 1 When I run without the debugger I get this error. File "./casco.py", line 62, in process if accountNbr == int(acct): ValueError: invalid literal for int(): " Can someone explain? From e0427417 at student.tuwien.ac.at Mon Nov 20 03:54:41 2006 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Mon, 20 Nov 2006 09:54:41 +0100 Subject: a few extensions for the itertools In-Reply-To: References: <4560bfb0$0$10578$3b214f66@tunews.univie.ac.at> Message-ID: <45616cf4$0$10578$3b214f66@tunews.univie.ac.at> Steven D'Aprano wrote: > On Sun, 19 Nov 2006 21:35:24 +0100, Mathias Panzenboeck wrote: > >> I wrote a few functions which IMHO are missing in python(s itertools). >> >> You can download them here: >> http://sourceforge.net/project/showfiles.php?group_id=165721&package_id=212104 >> >> A short description to all the functions: >> >> icmp(iterable1, iterable2) -> integer >> Return negative if iterable1 < iterable2, >> zero if iterable1 == iterable1, >> positive if iterable1 > iterable1. > > > What does it mean for an iterable to be less than another iterable? That > it has fewer items? How do these two iterables compare? > > iter([1, 2, None, "foo", 3+2j]) > > def ones(): > while 1: > yield 1 > > Which is smaller? > > it's like cmp on lists, but on iterables. [1,2,3] < [1,2,4] [1,2,3] < [1,2,3,0] ... > >> isum(iterable, start=0) -> value >> Returns the sum of the elements of a iterable >> plus the value of parameter 'start'. When the >> iterable is empty, returns start. > > > You mean just like the built-in sum()? > No, because the builtin sum can't handle iterables other than lists. Or dose it? Hmm, maby it dose since any new version and I didn't mention it. >>>> sum(xrange(12), 1000) > 1066 > > >> iproduct(iterable, start=0) -> value >> Returns the product of the elements of a iterable >> times the value of parameter 'start'. When the >> iterable is empty, returns start. > > If I recall, product() was requested about the same time that sum() was > introduced, and Guido rejected it as a built-in because it was really only > useful for calculating geometric means, and it is easy to do if you need > it: > > def product(it, start=1): > # default value of 1 is more sensible than 0 > # 1 is the multiplicative identity > p = start > for x in it: > p *= x > return p > > >> forall(predicate, iterable, default=True) -> bool >> Returns True, when for all elements x in iterable >> predicate(x) is True. When the iterable is empty, >> returns default. >> >> >> forany(predicate, iterable, default=False) -> bool >> Returns True, when for any element x in iterable >> predicate(x) is True. When the iterable is empty, >> returns default. > > > I vaguely recall plans for all() and any() builtins -- perhaps for Python > 2.5? > all() and any() don't get predicate functions as arguments. > >> take(n,iterable) -> iterator >> returns a iterator over the first n >> elements of the iterator > > Just like itertools.islice(iterable, n). > >>>> list(itertools.islice(xrange(10), 5)) > [0, 1, 2, 3, 4] > ok, ok, ok. I have overseen that. > >> drop(n,iterable) -> iterable >> drops the first n elemetns of iterable and >> return a iterator over the rest > > Just like itertools.islice(iterable, n, None) > >>>> list(itertools.islice(xrange(20), 15, None)) > [15, 16, 17, 18, 19] > > (Aside: I think islice would be so much cleaner if it took keyword > arguments.) > > > >> heads(iterable) -> iterator over all heads >> tails(iterable) -> iterator over all tails > > What would you use these for? > > >> fcain(funct,*functs) -> function(...,***) >> fcain(f1,f2,...,fn)(*args,*kwargs) equals f1(f2(...fn(*args,*kwargs))) > > > The usual term for this is function composition. > > From sjmachin at lexicon.net Sun Nov 19 06:39:25 2006 From: sjmachin at lexicon.net (John Machin) Date: 19 Nov 2006 03:39:25 -0800 Subject: Finding skilled pythonistas for micro-jobs? References: <1163895209.986877.13820@f16g2000cwb.googlegroups.com> Message-ID: <1163936364.875248.14590@h54g2000cwb.googlegroups.com> darran wrote: > I'm a partner in a design and technology studio that creates > large-scale interactive exhibits for museums. We are agile - by > choice. For big 6-12 month projects, we try and secure exceptional > python talent on contract. The python job board addresses this need. > > Every few weeks though I run up against a bite-sized programming > problem begging to be farmed out by our small company. The tasks > themselves span the gamut from data wrangling (format conversions) to > SWIG wrappers to Twisted to pyOpenGL. Often the task is 1 or 2 days of > work. Not really big enough to warrant a job search, a contract, or > even someone's full-time attention. The type of problem that is > perfectly suited to a CS student or daytime programmer looking to make > some extra money. Presently, when one of these jobs pops up, I just > add 8-16 hours to my work week - much to the dismay of my 3-year old > daughter who'd rather I pay someone and go to the park. The nice thing > though about our bite-sized jobs is that the goals are perfectly clear > because we are religious in our use of unit testing and test-driven > development. > > Any suggestions then for locating skilled Python/C++ programmers for > these small (micro) jobs? > A few entries from my own cynic's dictionary: Agile: the accounts dept displays fancy footwork when the bill is submitted Religious: Religions in IT come and go; the only tenets universally held by customer management have always been the Divine Right of Kings and Papal Infallibility, both applied of course only to themselves Clear goals, unit testing as applied to "data wrangling" -- a nonsense. Specs are prepared that are only tangentially relevant to the task and have obviously not been derived from any inspection of the data. Example (had allegedly been peer reviewed and mgt reviewed): "Placenames [in Australia] shall be validated to contain only letters and spaces" [or words to that effect] -- never mind no mention of case. Never mind that a moment's armchair reflection would have indicated that apostrophe and hyphen might be reasonable candidates. Australia is not heavily populated. Then (and now) the full list of placenames and postcodes needed for the application was printed at the back of larger-city phone directories, as found on the desks of "business analysts". It was available on floppy disk and in paper booklets from the Post Office. I believe that it was even available in Braille, so that the proverbial Blind Freddie would have been able to tell them that the *first* entry was [then] "A1 MINE SETTLEMENT". Cheers, John From george.sakkis at gmail.com Fri Nov 10 21:53:50 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 10 Nov 2006 18:53:50 -0800 Subject: Inheritance Question References: Message-ID: <1163213630.258725.129890@i42g2000cwa.googlegroups.com> Gabriel Genellina wrote: > If walking in general, have some common structure, you can put the > "sketch" on Legs and let the derived classes "fill the gaps". This is > known as "Template Method Pattern" - look for it. Or if you'd rather see a concrete example, here's how your toy example would look refactored using the template pattern: class Creature(object) def run(): pass def walk(): # lots of commands # that do not depend on the # number of legs but definitely # have to do with walking self._specialized_walk(*args, **kwds) # more commands def _specialized_walk(self, *args): raise NotImplementedError class UnipedalCreature(Creature): def _specialized_walk(self, *args, **kwds): # blahblah class BipedalCreature(Creature): def _specialized_walk(self, *args, **kwds): # blahblah HTH, George From eopadoan at altavix.com Wed Nov 29 12:52:01 2006 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Wed, 29 Nov 2006 15:52:01 -0200 Subject: How to detect what type a variable is? In-Reply-To: <456DC03D.7040107@tim.thechases.com> References: <1164814586.113454.144090@l12g2000cwl.googlegroups.com> <1164818738.403393.112900@j44g2000cwa.googlegroups.com> <456DC03D.7040107@tim.thechases.com> Message-ID: > > One might prefer to check for string-ness, as strings can > duck-type somewhat like lists: > > my_list = ['my', 'brain', 'hurts'] > my_string = 'Are you the brain specialist?' > > for test in [my_list, my_string]: > try: > for thing in test: > process_list_item(thing) > except Exception: #whatever flavor you want The exception should be the one that process_list_item raises when it receives a string instead of a list. if you want to treat strings and list in different ways, maybe it means that you are doing different operations on then, like appendind things to the list or whatever. If not, than you maybe want to test the types. > process_string(thing) # not called because > #strings are iterable What if you invert your code? for test in [my_string, my_list]: try: process_string_item(thing) #suppose process_string_item does some string operation on a list and gets this # exception - because if not, I see no meanning in distinguishing then except ValueError: for thing in test: process_list_item(thing) But maybe you have a reason to do things to a string that could be done to a list without raising an exception, but you dont want to do this to *that* list. My sugestion was to think if there is another way, and maybe you are right. -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt Blog: http://edcrypt.blogspot.com Jabber: edcrypt at jabber dot org ICQ: 161480283 GTalk: eduardo dot padoan at gmail dot com MSN: eopadoan at altavix dot com From yqiang at gmail.com Tue Nov 7 16:49:50 2006 From: yqiang at gmail.com (Yi Qiang) Date: Tue, 7 Nov 2006 13:49:50 -0800 Subject: Compiling python 2.5 on OS X 10.4.8 with bsddb support Message-ID: <3af8969a0611071349m338056a4hc194830e571e721c@mail.gmail.com> Hi guys, I am trying to compile python 2.5 on my OSX machine so it includes the bsddb module. Currently, when I type 'import bsddb' I get the following traceback: /Users/yi/Software/sage-1.4.1.2/local/lib/python2.5/bsddb/__init__.py in () 49 from bsddb3.dbutils import DeadlockWrap as _DeadlockWrap 50 else: ---> 51 import _bsddb 52 from bsddb.dbutils import DeadlockWrap as _DeadlockWrap 53 except ImportError: : No module named _bsddb I have the db3 and db4 packages installed from macports. What else must I do to get this working? Thanks, Yi From __peter__ at web.de Fri Nov 10 09:05:52 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Nov 2006 15:05:52 +0100 Subject: Back Slash not allowed at the end of raw string? References: Message-ID: yuhao wrote: > I'm using Python 2.5 on Windows XP Pro. > While testing for strings, I got the following result: > >>>> r'c:\' > SyntaxError: EOL while scanning single-quoted string > what does this message mean? I'm not using any single quote in the > statement. It this a bug or by design? http://effbot.org/pyfaq/why-can-t-raw-strings-r-strings-end-with-a-backslash.htm From ronrsr at gmail.com Mon Nov 27 14:48:09 2006 From: ronrsr at gmail.com (ronrsr) Date: 27 Nov 2006 11:48:09 -0800 Subject: can't get cgi values In-Reply-To: References: <1164652134.826957.80980@h54g2000cwb.googlegroups.com> Message-ID: <1164656888.974302.21120@14g2000cws.googlegroups.com> Thank you, all. that was very helpful, and did solve many of my problems. I was addressing the dict with () rather than []. I'm still having one problem, though -- extracting the keywords. NOw, if you check the value for Form below, you'll see there is more than one keyword entry. When I do: keywords = form["keywords"] - what sort of data structure do I get back? th anks so much again. -rsr- if form.has_key("keywords"): keywords = str(form["keywords"].value) else: keywords = "k" fileHandle.write("here comes keywords:") fileHandle.write(str(keywords)) fileHandle.write("keyword info"); fileHandle.write(str(form.has_key("keywords"))) fileHandle.flush() > here's the info I know: > > form = FieldStorage(None, None, [MiniFieldStorage('zid', '17'), > MiniFieldStorage('keywords', 'aAUA'), MiniFieldStorage('keywords', > 'aBOS'), MiniFieldStorage('citation', 'The Earth Times Monthly, > April 2002\\r\\n \\r\\n \r\n '), > MiniFieldStorage('quotation', 'Farm support goes mainly to a relatively > small number of agri-businesses, many of them large corps. Yet these > subsidies are 6 times what rich countries provide in foreign aid to a > developing world that includes 5 billion people.\\r\\n \r\n > '), MiniFieldStorage('updatebutton', 'Update')]) > form.has_key("citation") = True > > From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Nov 10 21:16:43 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 11 Nov 2006 03:16:43 +0100 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> <4rjlkqFrlskqU1@mid.individual.net> <4rk5giFrerjfU1@mid.individual.net> Message-ID: <4rkq4bFrfp4kU1@mid.individual.net> Steven D'Aprano wrote: > And just for the avoidance of doubt, Python "x == blue or red or > yellow" is semantically equivalent to: > > (x == blue) or bool(red) or bool(yellow) Yep, got it. Shame on me, it's so obvious now :) Regards, Bj?rn -- BOFH excuse #317: Internet exceeded Luser level, please wait until a luser logs off before attempting to log back on. From xi at gamma.dn.ua Sat Nov 18 15:30:26 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Sat, 18 Nov 2006 22:30:26 +0200 Subject: A python IDE for teaching that supports cyrillic i/o In-Reply-To: References: <20061118190104.GA29614@58sirius016.dc.ukrtel.net> Message-ID: <20061118203026.GC3393@58sirius016.dc.ukrtel.net> On Sat, Nov 18, 2006 at 01:22:44PM -0600, Larry Bates wrote: > Oleg Broytmann wrote: > > On Sat, Nov 18, 2006 at 09:01:04PM +0200, Kirill Simonov wrote: > >> Could anyone suggest me a simple IDE suitable for teaching Python as a > >> first programming language to high school students? > > > > Does it have to be an IDE? Wouldn't it be better to use a simple text > > editor + command line? > > > > Oleg. > Not sure about cyrillic and I don't mean if you are looking for Windows > IDE, but I'm impressed with Pyscripter: > > http://mmm-experts.com/Products.aspx?ProductId=4 PyScripter does, indeed, look nice, but unfortunately it appeared to have similar issues with cyrillic support. Thank you anyway for the suggestion. Thanks, Kirill From wierd_joe at spamhoo.com Sat Nov 25 03:32:13 2006 From: wierd_joe at spamhoo.com (Spiro) Date: Sat, 25 Nov 2006 09:32:13 +0100 Subject: Inheritance and recursion problem Message-ID: Hi all, i'm trying to make some user interface objects in python. I have classes XWindow and XMainWindow(XWindow) (XMainWindow inherited from XWindow) XWindow have all drawing functionality and Windows[] object which holds all child windows. Function Draw looks like this: def Draw(self): self.Back.blit for wnd in self.Windows: wnd.Draw(OffsetX, OffsetY) Now in main module i make objects: RootWindow=XWindow() MW=XMainWindow() RootWindow.Widnows.append(MW) Now the problem: When i call RootWindow.Draw() he calls wnd.Draw where wnd is XMainWindow from RootWindow's Windows[] collection. Now, we are in MW's Draw and MW's Windows[] collection should be empty but somehow he has itself (well, new instance of XMainWindow) in this collection and i got unlimited reference. ... While writing this post i tried something: instead of using RootWindow.Windows.append(MW) i used RootWindow.Windows=[MW] and now it's OK. I'm happy now, my code works, but i don't know what was happening there: why append made new instance of object instead of passing existing object. From mail at microcorp.co.za Mon Nov 13 02:08:33 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 13 Nov 2006 09:08:33 +0200 Subject: Random image text generation? References: <4557a186$0$5806$4d3efbfe@news.sover.net> Message-ID: <000e01c707a6$76520200$03000080@hendrik> From: "Leif K-Brooks" wrote: > Steven D'Aprano wrote: > > For a text only solution, consider putting up a natural language question > > such as: > > > > What is the third letter of 'national'? > > What is four plus two? > > How many eggs in a dozen? > > Fill in the blank: Mary had a little ____ its fleece was white as snow. > > Cat, Dog, Apple, Bird. One of those words is a fruit. Which one? > > That wouldn't work as a true CAPTCHA (Completely Automated *Public* > Turing test to tell Computers and Humans Apart), since making the list > of questions and answers public would defeat its purpose. you could consider keeping these answers secret - the spammers would then be stymied... From mirandacascade at yahoo.com Mon Nov 20 02:31:04 2006 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 19 Nov 2006 23:31:04 -0800 Subject: ElementSOAP and Message-ID: <1164007864.239490.20810@k70g2000cwa.googlegroups.com> 1) Is it correct that none of the examples in the ElementSOAP tutorial: http://effbot.org/zone/elementsoap-1.htm include an example in which the SOAP message that contains the request includes a block? 2) If one wanted to make use of ElementSOAP, and one wanted it to produce a SOAP message that includes a would the general outline be: a) use ElementTree to create and populate the element b) insert the element as a subelement of envelope in the SoapService class I think much of my confusion stems from my lack of understanding of SOAP. As I understand it, is an optional part of a SOAP message. I'm pretty sure that 'optional' at a minimum means that not all SOAP messages must contatin a . But does 'optional' mean more than that? Does it mean that one could get by without ever having to produce a SOAP message that includes a ? Or, are there some webservices where if one didn't include a in the SOAP message, the webservice would not work? Thank you. From fredrik at pythonware.com Sat Nov 25 16:12:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 25 Nov 2006 22:12:43 +0100 Subject: The Python Papers Edition One In-Reply-To: <1164471238.033790.243890@14g2000cws.googlegroups.com> References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <1164106267.882164.124670@h48g2000cwc.googlegroups.com> <1164156093.359433.315790@e3g2000cwe.googlegroups.com> <1164471238.033790.243890@14g2000cws.googlegroups.com> Message-ID: Noah Slater wrote: > Which is more important to the Python comunity... the community definitely don't need more random usenet posters who's only contribution is to complain whenever someone tries to do some- thing. this thread is an embarrassment for the Python community; you should all be ashamed of yourself. From aahz at pythoncraft.com Thu Nov 30 14:01:06 2006 From: aahz at pythoncraft.com (Aahz) Date: 30 Nov 2006 11:01:06 -0800 Subject: Python spam? Message-ID: Anyone else getting "Python-related" spam? So far, I've seen messages "from" Barry Warsaw and Skip Montanaro (although of course header analysis proves they didn't send it). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From gnewsg at gmail.com Fri Nov 10 13:17:10 2006 From: gnewsg at gmail.com (billie) Date: 10 Nov 2006 10:17:10 -0800 Subject: RAW network programming under Windows In-Reply-To: <1162769348.785276.294790@h48g2000cwc.googlegroups.com> References: <1162759117.346975.255000@f16g2000cwb.googlegroups.com> <1162769348.785276.294790@h48g2000cwc.googlegroups.com> Message-ID: <1163182629.955072.170690@h54g2000cwb.googlegroups.com> sturlamolden wrote: > You can try to install "Windows Services for Unix 3.5" (aka SFU 3.5). > It transforms your Windows into a certified UNIX (not just a Unix > clone). SFU 3.5 has a full BSD socket API (derived from OpenBSD), not > just Winsock. As the POSIX subsystem in SFU 3.5 is not layered on top > of the Win32 subsystem, but talks directly to the NT kernel, > restrictions in Winsock should not affect the BSD sockets in SFU 3.5. > This behaviour is different from e.g. Cygwin, where the "Unix APIs" are > layered on top of the Win32 subsystem. It isn't exactly what I'm searching for but thanks anyway. > In any case, I hope you are aware that spoofing IP packets gives you > bad karma. No problem about it. I'm just a lover of low-level network programming. =) From mike at hobbshouse.org Fri Nov 10 14:33:42 2006 From: mike at hobbshouse.org (Michael Hobbs) Date: Fri, 10 Nov 2006 13:33:42 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> Message-ID: <4554D416.70408@hobbshouse.org> Ron Adam wrote: > The faq also pointed out a technical reason for requiring the colon. It makes > the underlying parser much easier to write and maintain. This shouldn't be > taken to lightly in my opinion, because a simpler easer to maintain and more > reliable python parser means development time can be spent improving the > language in other areas instead of fixing parsing problems every time a new > feature is added that might be used in a conditional expression. > Not to be too picky about it, but the FAQ was referring to editor parsers, not the parser used by Python itself. The Python parser could easily change its grammar to make the colon optional. I find the editor parsing excuse to be weak since most editors tend to get hung up on Python code anyway, regardless of the colons. (Except for the ones that are specifically written to support Python, or are insanely programmable, like emacs.) In fact, I find that my editor usually gets confused when it comes across colons in dictionary literals or lambda expressions. If it just stuck to looking at the indentation, instead of trying to play off syntax tricks, it would behave much better. - Mike From bignose+hates-spam at benfinney.id.au Wed Nov 8 20:35:09 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 09 Nov 2006 12:35:09 +1100 Subject: is this the right way to do subclasses? References: <45522074$0$17101$c3e8da3@news.astraweb.com> Message-ID: <871wodmmgi.fsf@benfinney.id.au> John Salerno writes: > Ok, back to my so-called "game." I'm just curious if I've > implemented the subclasses properly, because it seems like an awful > lot of repetition with the parameters. And again, if I want to add a > new attribute later, I'd have to change a lot of things. I can't > help but get the feeling that I'm doing something very > inefficiently. This is another reason why passing the "stats" values as a mapping object is a good alternative. > class Character(object): > def __init__(self, name, strength, dexterity, intelligence): > self.name = name > self.health = 10 > self.strength = strength > self.dexterity = dexterity > self.intelligence = intelligence class Character(object): stat_keys = ['strength', 'dexterity', 'intelligence'] def __init__(self, name, stats): self.name = name self.health = 10 self.stats = {} for (key, value) in [(k, stats.get(k)) for k in stat_keys]: setattr(self, key, value) > class Fighter(Character): > def __init__(self, name, strength, dexterity, intelligence): > Character.__init__(self, name, strength, dexterity, intelligence) > self.health += 2 > self.strength += 1 class Fighter(Character): def __init__(self, name, stats): Character.__init__(self, name, stats) self.health += 1 self.strength += 1 et cetera. All you need to do to add a new type of "stat" is to add a new item to the 'stat_keys' list in Character. -- \ "I bought a self learning record to learn Spanish. I turned it | `\ on and went to sleep; the record got stuck. The next day I | _o__) could only stutter in Spanish." -- Steven Wright | Ben Finney From python.list at tim.thechases.com Wed Nov 1 09:35:47 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 01 Nov 2006 08:35:47 -0600 Subject: Make all files extension lower by a given directory name In-Reply-To: <20061101141648.38737.qmail@web15001.mail.cnb.yahoo.com> References: <20061101141648.38737.qmail@web15001.mail.cnb.yahoo.com> Message-ID: <4548B0C3.3040801@tim.thechases.com> >>> fullname = name[:len(name) - 1] + ext.lower() >> are you sure you want to strip off the last character in the actual >> filename? should "FOO.BAR" really be turned into "FO.bar" ? >> name[:len(name) - 1] can be written name[:-1], btw. >>> os.rename(os.path.join(path, file), os.path.join(path, fullname)) >>> >>> I know this code is lame >> except for the potential bug, and possibly the lack of error handling >> for the os.rename call, I'm not sure why you think that. >> > > thanks a lot! > > strip off the last character because if simply add name and > ext I got result like "FOO..bar", there are two dots. I'm When you split the filename and extension, the dot/separator remains as part of the extension. If you recombine the two pieces, you shouldn't try and add a dot back in. The code you posted originally doesn't do this, but you may have tweaked the original code before posting to the list. If anything, you'd want to strip the dot off the left side of the extension rather than try and monkey with the right side of the filename portion. >>> os.path.splitext('hello.txt') ('hello', '.txt') >>> help(os.path.splitext) Help on function splitext in module ntpath: splitext(p) Split the extension from a pathname. Extension is everything from the last dot to the end. Return (root, ext), either part may be empty. -tkc From steve.ingram at tnei.co.uk Sat Nov 11 15:38:07 2006 From: steve.ingram at tnei.co.uk (Steve Ingram) Date: Sat, 11 Nov 2006 20:38:07 -0000 (UTC) Subject: Close program built with py2exe Message-ID: <1569.80.46.127.179.1163277487.squirrel@www.tnei.co.uk> Hiya, I've got a problem with a program I've written and want to distribute. It uses a wxPython dialog and I've built a distribution version with py2exe. Problem is when I run the .exe under windows I can only stop the program completely using the task manager. When I close the dialog and check the task manager, there is still a running process. I think this is probably the python interpreter that is still running. Can't find any help anywhere, does anyone know how to get the dialog to kill the process properly?? Ta very much, Steve From ask at me Thu Nov 2 00:35:32 2006 From: ask at me (alf) Date: Wed, 01 Nov 2006 23:35:32 -0600 Subject: can I import the module twice (under differnet names) Message-ID: Hi, wonder if in the python I could treat modules imorts like classes instances. It means I could import it twice or more times under different names. -- alfz1 From 2huggie at gmail.com Sun Nov 26 04:55:10 2006 From: 2huggie at gmail.com (Timothy Wu) Date: Sun, 26 Nov 2006 17:55:10 +0800 Subject: Generator question In-Reply-To: References: Message-ID: On 11/26/06, Robert Kern wrote: > > > The only thing that the last line does is *create* a new generator object. > You > need to actually iterate over it and yield its values. E.g. > > > In [2]: def test_gen(x): > ...: yield x > ...: x -= 1 > ...: if x != 0: > ...: for y in test_gen(x): > ...: yield y > ...: > ...: > > In [3]: list(test_gen(3)) > Out[3]: [3, 2, 1] Ha-HA, that makes perfect sense I guess. Though in my opinion the definition makes the code a bit harder to read. Thanks for the explanation. Timothy -------------- next part -------------- An HTML attachment was scrubbed... URL: From otw67 at xs4all.nl Fri Nov 10 04:30:15 2006 From: otw67 at xs4all.nl (ruud habets) Date: Fri, 10 Nov 2006 10:30:15 +0100 Subject: python wiki question Message-ID: <455446a7$0$335$e4fe514c@news.xs4all.nl> Hi, Does anybody know how to determine if a wiki page is a redirectpage using the wikipedia-scripts? It must be something like if IsRedirectPage() == False: text_file.write("\n") But I cannot seem to get it working. thnx Ruud From fredrik at pythonware.com Thu Nov 16 02:40:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 08:40:27 +0100 Subject: Decimal() instead of float? In-Reply-To: <017d01c7094b$86032a20$03000080@hendrik> References: <1163294604.4675.4.camel@pepper><1163322853.760315.51040@k70g2000cwa.googlegroups.com> <455b82a0$0$7054$c3e8da3@news.astraweb.com> <017d01c7094b$86032a20$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > Nothing wrong with doing that - its not as if you are going to arithmetic with > them - adding my id to yours is generally not very useful... internal rowid's are best treated as pointers, though. they're more like memory addresses than labels. (from a design perspective, it's not entirely obvious that it's a good idea to use rowid's to point *into* the database from the outside, but that's another story). From eternalsquire at comcast.net Mon Nov 6 22:47:48 2006 From: eternalsquire at comcast.net (The Eternal Squire) Date: 6 Nov 2006 19:47:48 -0800 Subject: Python Distilled In-Reply-To: <1162860101.746321.73770@h54g2000cwb.googlegroups.com> References: <1162790565.418382.237050@m73g2000cwd.googlegroups.com> <08Odnc6j7uKLxtLYnZ2dnUVZ_oydnZ2d@comcast.com> <1162860101.746321.73770@h54g2000cwb.googlegroups.com> Message-ID: <1162871268.604656.306610@h48g2000cwc.googlegroups.com> Try also Diet Python on SourceForge. It's the first step toward a shrunken Python for embedded Win32 systems. Cheers, The Eternal Squire Simon Wittber wrote: > > http://www.python.org/dev/summary/2006-09-16_2006-09-30/#shrinking-python > > Excellent, just what I was hoping for. Thanks! > > -Sw. From boris.smirnov at gmail.com Thu Nov 9 11:53:54 2006 From: boris.smirnov at gmail.com (boris.smirnov at gmail.com) Date: 9 Nov 2006 08:53:54 -0800 Subject: extract text from a string In-Reply-To: <12l6ku8ahpave08@corp.supernews.com> References: <1163087125.176931.296440@h54g2000cwb.googlegroups.com> <12l6ku8ahpave08@corp.supernews.com> Message-ID: <1163091234.372222.37300@h48g2000cwc.googlegroups.com> Thank you very much. I needed this kick. :) Rg, Boris Grant Edwards nap?sal(a): > On 2006-11-09, boris.smirnov at gmail.com wrote: > > Hallo all, > > > > I have tried for a couple of hours to solve my problem with re but I > > have no success. > > > > I have a string containing: "+abc_cde.fgh_jkl\n" and what I need to > > become is "abc_cde.fgh_jkl". Could anybody be so kind and write me a > > code of how to extract this text from that string? > > >>> s = "+abc_cde.fgh_jkl\n" > >>> s[1:-1] > 'abc_cde.fgh_jkl' > > -- > Grant Edwards grante Yow! ... I think I'm > at having an overnight > visi.com sensation right now!! From no-spam at no-spam-no-spam.invalid Thu Nov 9 15:37:53 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 09 Nov 2006 21:37:53 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <1163072637.924217.90610@h54g2000cwb.googlegroups.com> References: <1163072637.924217.90610@h54g2000cwb.googlegroups.com> Message-ID: Paul Boddie wrote: > robert wrote: >> Shane Hathaway wrote: >>> of multiple cores. I think Python only needs a nice way to share a >>> relatively small set of objects using shared memory. POSH goes in that >>> direction, but I don't think it's simple enough yet. >>> >>> http://poshmodule.sourceforge.net/ >> interesting, a solution possibly a little faster than pickling - but maybe only in selected >> situations. Made already experiments with pickling through shared memory. > > What did you discover in your experiments? I'd certainly suspect that > pickling is going to add an unacceptable degree of overhead in the kind > of application you're attempting to write (using a shared data > structure with random access properties), and I'll admit that I haven't > really had to deal with that kind of situation when using my own > pickle-based parallelisation solutions (which involve communicating > processes). > >> With "x = posh.share(x)" an object tree will be (deep-)copied to shared mem ( as far as >> objects fullfil some conditions http://poshmodule.sourceforge.net/posh/html/node6.html: is >> this true for numpy arrays?) > > My impression is that POSH isn't maintained any more and that work was > needed to make it portable, as you have observed. Some discussions did > occur on one of the Python development mailing lists about the > possibility of using shared memory together with serialisation > representations faster than pickles (which also don't need to be > managed as live objects by Python), and I think that this could be an > acceptable alternative. > >> Every object to be inserted in the hot tunnel object tree has to be copied that same style. >> Thus ~pickling, but somewhat easier to use. > > If my understanding of "hot tunnel object tree" is correct, you're > really wanting fast access involving mutual exclusion to some shared > data structure. At this point it becomes worth considering some kind of > distributed object technology (or even a database technology) where you > have to initialise the data structure and then communicate with an > object (or database) to perform operations on it, all for reasons I'll > explain shortly. > > In your ideal situation, you say that you'd have the data structure in > the same address space as a number of threads, and each thread would be > able to perform some algorithm on the data structure, but the pattern > of accessing the structure isn't an insignificant concern even where > you can assume that the overheads are generally low: reading and > writing things might be fast in the same address space, but if the > nature of access involves lots of locking, you'll incur quite a penalty > anyway. In other words, if each read or write to the structure involves > acquiring a lock for that operation in isolation, this could > significantly diminish performance, whereas if you can guarantee that > the granularity of locking is more coarse than having to occur upon > each read or write access - that there exist some high-level operations > that require consistency within the data structure - then reasonable > performance might be maintained. > > However, if the pattern of concurrent access is restricted to coarse > operations, where some entity has exclusive access to a potentially > large dataset, and where the overhead of the communication of inputs > and outputs to and from that entity is low in comparison to the cost of > performing such coarse operations, and where such operations are > themselves performed infrequently, then such a pattern coincides with > classic database or distributed object scenario. In other words, you > implement the operations acting on the data structure in a distributed > object (or as a database query or operation) and then invoke such > operations from separate processes. > > I hope this makes some sense. Generally, demands for high concurrent > performance using threads often ignore other important properties such > as reliability and scalability. Certainly, threads have an important > place - classically, this involved maintaining responsiveness in > graphical user interfaces - but even then, the background threads were > often detached and not competing for the same resources as the > foreground threads servicing the event loop. The only kinds of > situation I can think of right now which might benefit from uninhibited > random access to shared data structures might be things like > simulations or large-scale multi-user games, where an appropriate data > architecture cannot be decided in advance, but even then there are > approaches which attempt to mitigate the seemingly unpredictable nature > of access to shared data. Some thoughts may make reason, when one wants to trick the single GIL a little. But the length of the text tells us again to possibly get at least refcounting thread safe (within access restrictions) - or get rid of refcount - or do it an go the full path towards a GIL free Python. Besides some programming costs the speed cost would be that of a few LOCK INC's. Rumors tell not much - and almost nothing when not using non-SMP threading. I'd like to see experimental data regarding the speed. Found nothing on the web so far. And optimistic all lockfree basic datastructures (obmalloc's freelist, dicts, queues,..) could be built up for futher optimizations: http://64.233.183.104/search?q=cache:KUXW1Ya2duwJ:softwareforums.intel.com/ids/board/message%3Fboard.id%3D42%26message.id%3D68+SMP+%22LOCK+INC%22+speed&hl=de&gl=de&ct=clnk&cd=2 Little test: -------------------- #include #include #include volatile int x=0; clock_t c0,c1; time_t t0,t1; int main (int argc, char **argv) { int sum = 0, i, count = 1000000000; t0=time(&t0); c0=clock(); for (i = 0; i < count; ++i) { __asm lock inc x; // __asm inc x; sum += x; } c1=clock(); t1=time(&t1); // printf("%d\n", sum); printf("clocks: %d\n", c1-c0); printf("secs: %d\n", t1-t0); return sum; } -------------- 0040101F mov eax,3B9ACA00h 13: for (i = 0; i < count; ++i) { 14: __asm lock inc x; 00401024 lock inc dword ptr [_x (00408a00)] 15: sum += x; 0040102B mov edx,dword ptr [_x (00408a00)] 00401031 add esi,edx 00401033 dec eax 00401034 jne main+24h (00401024) 16: } --------------- results on a UP PIII : INC version: clocks: 7520 secs: 7 LOCK INC version: clocks: 36632 secs: 36 Its probably not much... -robert From jstroud at mbi.ucla.edu Sat Nov 4 03:56:02 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 04 Nov 2006 08:56:02 GMT Subject: Programming Language that is Spreadsheet/Table Based In-Reply-To: <1162626260.236167.157920@m73g2000cwd.googlegroups.com> References: <1162588208.533235.266100@k70g2000cwa.googlegroups.com> <1162626260.236167.157920@m73g2000cwd.googlegroups.com> Message-ID: Gerard Flanagan wrote: >> py> # the following is probably the trickiest, should it return a Table >> py> # should it be illegal? >> py> # should t['Last'] be the way to take the "slice" and get the col? >> py> t[None, 'Last'] # 1d slice returns list (2nd dim. explicit) >> ['Barker', 'Burnet', 'Danson', 'Cooper'] > > I can imagine manipulating columns at the Table creation stage - > insert, append, delete column - but after that I think you would be > dealing with rows more often. Personally, if I needed columns I would > be happier with a list comprehension: > [ (row['Last'], row['Age']) for row in t ] > etc. To make a table from list comprehension in this way seems like it would require some redundancy because a list comprehension only gets you a list (of rows or lists). It seems if you wanted to work with your 2d selection of data, then you would want to get a table back: data = [ (row['Last'], row['Age']) for row in t ] t2 = Table(('Last','Age'), data) This seems, to me, to separates selection in the 2 dimensions and makes it "backwards": data = [ (row['Last'], row['Age']) for row in t[1:3]] t2 = Table(('Last','Age'), data) So a function would be needed to group the selection in a way that reflects the organization of the table: t2 = t.subtable((1,3), ('Last','Age')) But then, since the latter seems a natural consequence of using list comprehension for selection, how might one distinguish a range of columns if not by a verbose function name? t2 = t.subtable_with_column_range((1,3), ('Last','Age')) The concept of slicing seems to take care of this. Maybe t2 = t.subtable(slice(1,3), slice('Last','Age')) But this begins to seem awkward and verbose to boot. Any suggestions on adapting your idea of list comprehension to generate subtables? > eg. like: > > http://buzhug.sourceforge.net/ > >> py> t2 = t[1:3, ('First', 'Age')] # 2d slice returns a new Table >> py> t3 = t[1:3,'First':'Age'] # shorthand to take a swath of columns >> py> t3 = t[1:3, 0:2] # if we know what column numbers we want instead > > t[1:3][0:2] and so on would be more intuitive to me, possibly > t[1:3]['First':'Age'] This looks better than my slicing, and to argue with it I'd have to break my own rules and point out that it would require making an intermediate table in the implementation. I am emulating numarray slicing closely, which itself is probably focused on implementation and speed. James From no-spam at no-spam-no-spam.invalid Fri Nov 10 06:48:51 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 10 Nov 2006 12:48:51 +0100 Subject: how is python not the same as java? In-Reply-To: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> Message-ID: gavino wrote: > both are interpreted oo langauges...... > Thinks the first FAQs and tutorials about Python answer this question in detail. Theoreticalls you'd start off thinking this: * Java is a stiff typing language (as old C/C++/Pascal... and even Perl are also ). * Python is a dynamic typing language - regarding almost all aspects. >From that each language can try to achieve some benefits of the other basic paradigm by becoming cramped. Practically: * you will type a Python programs >5x faster than the equivalent in Java. * This is true, at least when we assume that test code has to be done for a good program anyway (and/otherwise "pychecker" will neutralize most first-glance disadvantages of Python) * Jave (typed code) ist executed faster. Yet Python is even faster when using little C, Pyrex, ... That is probably what counts. Robert From http Fri Nov 3 14:29:36 2006 From: http (Paul Rubin) Date: 03 Nov 2006 11:29:36 -0800 Subject: Sorted and reversed on huge dict ? References: <1162580533.981364.211860@h54g2000cwb.googlegroups.com> Message-ID: <7xvelwib1b.fsf@ruckus.brouhaha.com> Fredrik Lundh writes: > items = d.items() > items.sort(key=operator.itemgetter(1), reverse=True) > > the items list would require a couple of megabytes for 150k dictionary > entries, or so. the key map needs some memory too, but the rest of > the sort is done in place. I think the OP's method avoided the key map. From will at willmcgugan.com Thu Nov 30 12:48:43 2006 From: will at willmcgugan.com (Will McGugan) Date: 30 Nov 2006 09:48:43 -0800 Subject: extremely slow array indexing? References: <1164907021.765969.129280@80g2000cwy.googlegroups.com> Message-ID: <1164908923.363433.43770@l39g2000cwd.googlegroups.com> Grace Fang wrote: > Hi, > > I am writing code to sort the columns according to the sum of each > column. The dataset is huge (50k rows x 300k cols), so i need to read > line by line and do the summation to avoid the out-of-memory problem. > But I don't know why it runs very slow, and part of the code is as > follows. I suspect it's because of array index, but not sure. Can > anyone > point out what needs to be modified to make it run fast? thanks in > advance! Array indexing is unlikely to be the culprit. Could it not just be slow, because you are processing a lot of data? With numbers those big I would expect to have enough time to go make a coffee, then drink it. If you think it is slower than it could be, post more code for optimization advice... Will McGugan -- http://www.willmcgugan.com From saptarshi.guha at gmail.com Wed Nov 8 20:22:58 2006 From: saptarshi.guha at gmail.com (sapsi) Date: 8 Nov 2006 17:22:58 -0800 Subject: Using Python from Cocoa App via PyObjc - numbers dont match... Message-ID: <1163035378.654266.287360@m73g2000cwd.googlegroups.com> Hi, I managed to create a python class and instantiate that from my Objective C Cocoa App (its not a python app). Essentially, i made two classes in IB and then another class(ogle) with outlets for these two. Now here is the implementation for ogle.m -(void)awakeFromNib { NSNumber *n=[NSNumber numberWithFloat:40.4]; NSLog(@"%@",n); NSNumber *b=[it2 printNok:n]; NSLog(@"%@",b); // } The first output in the console is 40.4 and the second -40.40000152587891. If i change the NSLog(s) to "%f",[n floatValue] (and the second likewise) the first is 40.400002 and the second is -40.400002. Why does this happen? Thanks Saptarshi p.s the python routine printNok, just returns the negative of the number i.e printNok: def printNok_(self, obj): return -obj From dlenski at gmail.com Fri Nov 10 09:55:15 2006 From: dlenski at gmail.com (Dan Lenski) Date: 10 Nov 2006 06:55:15 -0800 Subject: How to choose the right GUI toolkit ? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163106111.916021.103880@b28g2000cwb.googlegroups.com> Message-ID: <1163170515.451653.65120@m7g2000cwm.googlegroups.com> Eric Brunel wrote: > On Thu, 09 Nov 2006 22:01:51 +0100, Dan Lenski wrote: > > Tk 8.4 appears to use native Win32 widgets under Cygwin and native > > WinXP. > > It seems to depend on the widget type, and on what you call native... For > example, tk menus are definitely the native ones; tk scrollbars are the > native ones, but with the Win2k look (no XP look available yet); tk > buttons do not seem to be the native ones, as they don't act like "normal" > Windows buttons. So, basically, Tk is actually embedding the native Win2k menus, but it isn't actually embedding the native Win2k scrollbars... it's just emulating their look and feel? > > But it definitely doesn't use GTK widgets under Ubuntu with > > Gnome desktop. > > You seem to imply that GTK is "native" on Linux. It isn't, as can be seen > with the echoes of the "holy war" between Gnome and KDE that we often see > around here. As an aside, I personnally work on Linux and don't even use > any of these environments (both are too much Windows-like to my taste...). I didn't imply that GTK widgets are "native" on Linux. I implied that GTK widgets native under Gnome ;-) I was basing my assumption on an earlier poster who said that Tk 8.x can use native widgets on all supported platforms... so I assumed that under Gnome it should use GTK widgets. > > Is there a way to get it to do so? > > Not yet. But tcl/tk 8.5 will include the Tile extension including new > themable widgets. See here: > http://tktable.sourceforge.net/tile/screenshots/unix.html Good to know! I'm looking forward to 8.5. Dan From no-spam at no-spam-no-spam.invalid Wed Nov 8 11:25:26 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 08 Nov 2006 17:25:26 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <454bd36c$0$2364$9b622d9e@news.freenet.de> Message-ID: robert wrote: > Martin v. L?wis wrote: [..] > > Thanks for that info. That is interesting. > Thus even on x86 currently this LOCK is not used (just > (op)->ob_refcnt++) ) > > Reading this I got pinched: In win32ui there are infact Py_INC/DECREF's > outside of the GIL ! > And I have a severe crash problem with threaded apps - the problem is > only only on dual cores ! > That pointer probably will end a long search... In fact that it was in win32ui. Months I've search the bug strainedly, and this fancy discussion revealed it :-) From sjmachin at lexicon.net Sun Nov 5 13:31:12 2006 From: sjmachin at lexicon.net (John Machin) Date: 5 Nov 2006 10:31:12 -0800 Subject: finding the list of the matched strings In-Reply-To: References: <1162731282.327715.49800@f16g2000cwb.googlegroups.com> Message-ID: <1162751472.515380.139460@b28g2000cwb.googlegroups.com> James Stroud wrote: [snip] > I think I'm having some network problems. I'll try again. Also the > previous "attempt" had a typo (perhaps a freudian slip). Also this time you replied to the wrong thread :-) > > ",".join(some_list). > > By the way, don't name your own objects with the names of built-in > types, such as "list" or "str", etc. From carsten at uniqsys.com Sun Nov 12 12:52:21 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 12 Nov 2006 12:52:21 -0500 Subject: Py3K idea: why not drop the colon? In-Reply-To: <1163315927.963179.114030@m73g2000cwd.googlegroups.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163315927.963179.114030@m73g2000cwd.googlegroups.com> Message-ID: <1163353941.3497.45.camel@localhost.localdomain> On Sat, 2006-11-11 at 23:18 -0800, Doug wrote: > Michael Hobbs wrote: > > I think the colon could be omitted from every type of compound > > statement: 'if', 'for', 'def', 'class', whatever. Am I missing anything? > > > > Thanks, > > - Mike > > It is a very good idea as the colon is technically redundant (not > necessary for parsing, aside from one liners) and actually hurts > readability (and writeability). The "evidence" people cite for the > advantage of using a colon is research done by users of the ABC > language, python's predecessor. They forget that A) that was like 20 > years ago, Research being old does not automatically invalidate it. Old research is invalidated by newer research that invalidates it. > B) the language was designed for children, http://www.cwi.nl/archive/projects/abc.html does not mention children: "Originally intended as a language for beginners, it has evolved into a powerful tool for beginners and experts alike." > and C) the > keywords in ABC are IN ALL CAPS LIKE THIS (hurting readability and > writeability) and thus adding a colon obviously helps restore some > readability for users in that case but not in python's. So what are you saying? In a programming language that doesn't use all caps keywords, adding colons to block-beginning lines hurts readability, or it doesn't add any readability? In any case, that's an assertion that should be backed up by citing relevant research. > However, python is far too old to accept any fundamental changes to > syntax at this point. The source code for Python is openly available. If you are so convinced of the added readability from removing the colons, do the world a favor and make the necessary change, or hire somebody to make the change, to Python. -Carsten From laurent.pointal at limsi.fr Mon Nov 27 07:14:59 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 27 Nov 2006 13:14:59 +0100 Subject: Ruby/Python/REXX as a MUCK scripting language In-Reply-To: <4sr3neF111j0gU1@mid.individual.net> References: <2006112418112116807-zobeid@techiecom> <4sr3neF111j0gU1@mid.individual.net> Message-ID: Fred Bayer a ?crit : > > Tony Belding wrote: >> I'm interested in using an off-the-shelf interpreted language as a >> user-accessible scripting language for a MUCK. I'm just not sure if I >> can find one that does everything I need. The MUCK must be able to >> call the interpreter and execute scripts with it, but the interpreter >> must also be able to call functions in the MUCK code. And then >> there's the security issue that really worries me. . . I have to be >> able to limit what the interpreter can execute. I can't have my users >> running scripts that access the console, access the filesystem or >> sockets directly, or call libraries or other binaries outside the MUCK. >> >> Is this practical? I'm thinking of Ruby or Python for this, if they >> can meet the requirements. >> > > Don't forget Lua: www.lua.org > It fulfills your requirements and is easily embedable. > I Agree with F.Bayer, when reading OP post, I immediatly think about Lua. From robert.kern at gmail.com Fri Nov 10 01:51:30 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 10 Nov 2006 00:51:30 -0600 Subject: Printing to file, how do I do it efficiently? In-Reply-To: References: Message-ID: Cameron Walsh wrote: > Hi all, > > I have a numpy.array of 89x512x512 uint8's, set up with code like this: numpy questions are best asked on the numpy list, not here. http://www.scipy.org/Mailing_Lists > data=numpy.array([],dtype="uint8") > data.resize((89,512,512)) You might want to look at using numpy.empty() here, instead. > # Data filled in about 4 seconds from 89 image slices > > > > I first tried writing this data to a binary raw format (for use in a > program called Drishti) as follows: > > # The slow bit: > volumeFile=file("/tmp/test.raw","wb") > for z in xrange(Z): > for y in xrange(Y): > for x in xrange(X): > volumeFile.write("%c" %(data[z,y,x])) > volumeFile.close() > > That took about 39 seconds. > > My second attempt was as follows: > volumeFile = open("/tmp/test2.raw","wb") > data.resize((X*Y*Z)) # Flatten the array > for i in data: > volumeFile.write("%c" %i) > data.resize((Z,Y,X)) > volumeFile.close() > > This took 32 seconds. (For those of you unfamiliar with numpy, the > data.resize() operations take negligible amounts of time, all it does is > allow the data to be accessed differently.) No, if the total size is different, it will also copy the array. Use .reshape() if you want to simply alter the shape, not the total number of elements. > I'm guessing that the slow part is the fact that I am converting the > data to character format and writing it one character at a time. What > is a better way of doing this, or where should I look to find a better way? data.tostring() -- 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 mauriceling at acm.org Sat Nov 25 02:18:30 2006 From: mauriceling at acm.org (Maurice LING) Date: Sat, 25 Nov 2006 07:18:30 GMT Subject: The Python Papers Edition One In-Reply-To: References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <7xodqyn5kd.fsf@ruckus.brouhaha.com> <1164323350.988946.209350@l12g2000cwl.googlegroups.com> <16651e80611242126u55685813u7d77f299c738963e@mail.gmail.com> Message-ID: <4567ee43$1@news.unimelb.edu.au> Jerry Hill wrote: > On 11/25/06, Jerry Hill wrote: > >> On 23 Nov 2006 15:09:11 -0800, tleeuwenburg at gmail.com >> wrote: >> > Yes, it's true that you can't resell copies of The Python Papers for >> > personal profits, but you may derive from it, reproduce and propagate >> > it. You're quite right to point it out. >> >> My problem with this is that I can't use anything in your publication >> when working on commercial software. If I were to derive code from >> something in the Python Papers, my understanding is that I would be >> obligated to release it under a Creative Commons license. In fact, >> even if all I do is read an article and then incorporate concepts from >> it in my code, my understanding is that I may be creating a derivative >> work. >> >> Since the code that I write for work belongs to my employer, and may >> someday be sold, I need to be careful about the licensing issues. They >> might not be very happy with me if I wrote software for them that >> ended up being encumbered with a license they didn't like. I don't >> think there's much of a problem with Issue 1, since I don't think I'd >> end up copying the code in the 'Python Coding Idioms' article, and >> MontyLingua is GPL software and thus has its own licensing issues for >> commercial software. Still, if there was a useful article on, say, >> database or web interfaces, I would have to avoid it. If I have to >> avoid using any articles that might actually be useful in my >> professional life, I feel like I should probably just avoid the >> journal all together. If I've misrepresented the relevant copyright >> issues, I'd be happy for someone to correct me. >> As Steven mentioned -- anything you can read is copyrighted. The difference is whether is the copyright effective or enforceable. What do I mean by this? Without copyright, there will not be plagarism. Ask yourself this question, can you copy William Shakespeare's MacBeth and submit it as a literary work for a Master of Literary Arts degree? I believe the candidate will be expelled from university. William Shakespeare's MacBeth is still copyrighted work but not "enforceable" because it is pre-1900's work and the author had been dead for more than 50 years. Similarly, works in public domain are still copyrighted -- academically, using work in public domain without attribution (giving credits in the form of citations) is still plagarism. This means that everything you had read since the days of "ABC..." are copyrighted. That includes all codes you've seen in colleges etc etc. I am afraid that to avoid copyright altogether, as far as your work is concerned, you might have to seclude yourself in some pacific islands and re-discover mathematics and computer science all over again from 1 + 1 = 2, and 2 + 1 = 3, and so on. Even so, patents will still get you at the end. In copyright, there is fair use. There is no way of avoiding it totally -- how many ways are there to write a list comprehension? Copyright just says attribute credits when you use someone else's work within the limits of fair use; otherwise you might have to pay for it in the form of a licence, subject to the copyright owner. I believe you've done all these in college when writing your essays. I believe in most cases, a simple declaration like "This function is a re-implementation (or adaptation) of that found in " will suffice. Have you not read "The Python Cookbook", in book form or from the website? How do you attribute credits when you are using the codes? Cheers maurice From http Fri Nov 3 14:21:51 2006 From: http (Paul Rubin) Date: 03 Nov 2006 11:21:51 -0800 Subject: Sorted and reversed on huge dict ? References: <1162580533.981364.211860@h54g2000cwb.googlegroups.com> Message-ID: <7xd584l4j4.fsf@ruckus.brouhaha.com> vd12005 at yahoo.fr writes: > i would like to sort(ed) and reverse(d) the result of many huge > dictionaries (a single dictionary will contain ~ 150000 entries). Keys > are words, values are count (integer). > > i'm wondering if i can have a 10s of these in memory, Depends on how much memory your machine has. > or if i should proceed one after the other. Obviously that's more memory friendly if you can do it that way. > from itertools import izip > pairs = izip(d.itervalues(), d.iterkeys()) > for v, k in reversed(sorted(pairs)): > print k, v > > or will it be the same as building the whole list ? I think the above is pretty good. sorted necessarily builds and returns a list, but itervalues/iterkeys, izip, and reversed, just build small iterator objects. If the lists are really large, your next step after the above is probably to use an external sort, but 150000 entries is not that many, and anyway if sorting is a strain on available memory, then having the dicts in memory at all will probably also be a strain. Maybe you should start looking into storing the dict contents externally, such as in a database. From sjmachin at lexicon.net Thu Nov 9 20:34:19 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Nov 2006 17:34:19 -0800 Subject: pack a three byte int In-Reply-To: <1163120944.551169.293230@h48g2000cwc.googlegroups.com> References: <1163027401.386603.263030@k70g2000cwa.googlegroups.com> <1163120944.551169.293230@h48g2000cwc.googlegroups.com> Message-ID: <1163122459.492898.13090@e3g2000cwe.googlegroups.com> p.lavarre at ieee.org wrote: > Speaking as the OP, perhaps I should mention: > > > > [-3:] to [1:] is a minor cosmetic improvement > > To my eye, that's Not an improvement. > > '\x08' '\x01\x23\x45' '\x80' '\0' is the correct pack of (0x08, > 0x12345, 0x80, 0) because '\x01\x23\x45' are the significant low three > bytes of a big-endian x12345, thus [-3:]. > > The [1:] fact that we can keep the 3 significant bytes by tossing > exactly 1 byte away after rounding the bit length of that digital > number up to the nearest power of two which happens to be 4 = 3 + 1 is > merely incidental - not of central significance. I said *cosmetic* improvement and also said "obscures the underlying" need-to-know that 4 - 3 == 1 (which I didn't contemplate needing 2 paragraphs of laborious explanation). From leo at snorland.com Sun Nov 5 08:36:18 2006 From: leo at snorland.com (Snor) Date: 5 Nov 2006 05:36:18 -0800 Subject: Event driven server that wastes CPU when threaded doesn't In-Reply-To: References: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> Message-ID: <1162733778.448053.172820@m73g2000cwd.googlegroups.com> > You got a lot of long-winded replies, but the short reply is that > Twisted has packaged solutions for this. Seehttp://twistedmatrix.com/projects/core/enterprise > > "Twisted provides an interface to any Python DB-API 2.0 compliant > database through an asynchronous interface which allows database > connections to be used, and multiplexed by multiple threads, while still > remaining thread-safe for use with Twisted's event-based main loop. > Twisted Enterprise provides these services by leveraging Twisted > Internet's utilities for managing thread pools and asynchronous > programming." Thanks for this - exactly what I needed. Thanks for the other replies too even if they weren't so much help :) From sjmachin at lexicon.net Wed Nov 15 17:48:34 2006 From: sjmachin at lexicon.net (John Machin) Date: 15 Nov 2006 14:48:34 -0800 Subject: ANN: pyfaq 1.0b1 is now available References: Message-ID: <1163630914.818184.210590@e3g2000cwe.googlegroups.com> Fredrik Lundh wrote: > After incorporating more than 60 comments, adding a bunch of new > articles, and having made a ludicrous amount of minor edits and > tweaks, I'm happy to announce a first "beta" release of the new > Python FAQ: > > http://effbot.org/pyfaq/ > > Many thanks to everyone who's contributed this far! > UnicodeDecodeError, UnicodeEncodeError: I was about to ask mildly the other day whether a c.l.py poster had RTFFAQ when I thought "Hmmm long while since I'd RTFFAQ myself, better have a peep". Shock/horror; couldn't find "UnicodeEncodeError" -- why not? See below: FAQ: What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean? Python: Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 | >>> str(u'\xff') UnicodeError: ASCII encoding error: ordinal not in range(128) Python 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32 | >>> str(u'\xff') UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0: ordinal not in range(128) ======= P.S. Great job on the wiki, and yes a search facility a tad smarter than browser Ctrl-F would be a very good idea! Cheers, John From __peter__ at web.de Fri Nov 10 03:39:39 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Nov 2006 09:39:39 +0100 Subject: to Doctest as SystemExit is to Python References: <1163136324.202924.165630@k70g2000cwa.googlegroups.com> Message-ID: p.lavarre at ieee.org wrote: > Can I somehow tell doctest that it's time to quit? Hit Ctrl-C. Or raise a KeyboardInterrupt: import sys class ExitDoctest(KeyboardInterrupt): pass def f(what): """ >>> f("alpha") 'alpha' >>> f("e") 'e' >>> f("x") 'x' >>> f("X") 'X' >>> f("beta") 'beta' """ if what == "e": raise Exception elif what == "x": sys.exit() elif what == "X": raise ExitDoctest("You're in trouble") return what if __name__ == "__main__": import doctest try: doctest.testmod() except ExitDoctest, e: print >> sys.stderr, e Peter From gagsl-py at yahoo.com.ar Thu Nov 9 13:29:42 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 09 Nov 2006 15:29:42 -0300 Subject: newbie class-building question In-Reply-To: <1163075427.630088.247050@h54g2000cwb.googlegroups.com> References: <1163075427.630088.247050@h54g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061109152728.04158d68@yahoo.com.ar> At Thursday 9/11/2006 09:30, jrpfinch wrote: >I am constructing a simple class to make sure I understand how classes >work in Python (see below this paragraph). > >It works as expected, except the __add__ redefinition. I get the >following in the Python interpreter: > > >>> a=myListSub() > >>> a >[] > >>> a+[5] >Traceback (most recent call last): > File "", line 1, in ? >TypeError: 'str' object is not callable > >>> > > def __getattr__ (self,attrib): > return getattr(self.wrapped,attrib,'attribute not found') This is the culprit; should raise AttributeError when not found, not return a string. Just return getattr(self.wrapped, attrib) and let the error propagate. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From michael at stroeder.com Fri Nov 17 13:39:20 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 17 Nov 2006 19:39:20 +0100 Subject: Python v PHP for web, and restarting Apache? In-Reply-To: <1163783247.077263.8590@j44g2000cwa.googlegroups.com> References: <1163783247.077263.8590@j44g2000cwa.googlegroups.com> Message-ID: walterbyrd wrote: > I think I have read somewhere that using Python to develop > web-applications requires some restarting of the Apache server, whereas > PHP does not. Using Python to develop web-applications is a very broad topic. E.g. you don't have to restart Apache if you develop simple short-running CGI-BIN programs. With a long-running web app (e.g. with FastCGI) you might only kill the web app's process etc. Or you implement a graceful restart in your web app or... > Also, I seem to remember reading something about PHP being able to > recover from Apache restarting more easily than Python. As usual it depends. Ciao, Michael. From __peter__ at web.de Tue Nov 7 02:35:29 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Nov 2006 08:35:29 +0100 Subject: Nested Dictionary Sorting References: Message-ID: Sam Loxton wrote: > I am fairly new to the python language and am trying to sort a nested > Dictionary of a Dictionary which I wish to sort by value. The dictionary > does not have to be restructured as I only need it sorted in this way > for printing purposes. > > The following is an example of my Dictionary printed with 'print > dictionary.items()', where '2329513' is the key of the first hash, 'ops' > is the key of the second hash and '50.0' is the value of the second hash > which I would like to sort by: > [('2329513', {'ops': 20.0}), ('2329492', {'ops': '80'}), ('2329490', > {'ops': '50'})] > > I hope to sort these first keys by the value of the 'ops' key from > highest to lowest value to give the following result: > [('2329492', {'ops': '80'}), ('2329490', {'ops': '50'}), ('2329513', > {'ops': 20.0})] If Dennis' remarks don't apply because you simplified your problem for the post: >>> d = {'2329513': {'ops': 20.0}, '2329492': {'ops': '80'}, '2329490': {'ops': '50'}} >>> items = d.items() >>> def key(item): ... return item[1]["ops"] ... >>> items.sort(key=key, reverse=True) >>> items [('2329492', {'ops': '80'}), ('2329490', {'ops': '50'}), ('2329513', {'ops': 20.0})] Peter From george.sakkis at gmail.com Mon Nov 13 03:59:40 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 13 Nov 2006 00:59:40 -0800 Subject: Python 3000 idea -- + on iterables -> itertools.chain References: <1163385266.824914.265490@b28g2000cwb.googlegroups.com> Message-ID: <1163408380.747399.18750@h54g2000cwb.googlegroups.com> Fredrik Lundh wrote: > George Sakkis wrote: > > > The base object class would be one candidate, similarly to the way > > __nonzero__ is defined to use __len__, or __contains__ to use __iter__. > > > > Alternatively, iter() could be a wrapper type (or perhaps mixin) > > instead of a function, something like: > > so you're proposing to either make *all* objects respond to "+", or > introduce limited *iterator* algebra. If by 'respond to "+"' is implied that you can get a "TypeError: iterable argument required", as you get now for attempting "x in y" for non-iterable y, why not ? Although I like the iterator algebra idea better. > not sure how that matches the OP's wish for "mostly backwards > compatible" support for *iterable* algebra, really... Given the subject of the thread, backwards compatibility is not the main prerequisite. Besides, it's an *extension* idea; allow operations that were not allowed before, not the other way around or modifying existing semantics. Of course, programs that attempt forbidden expressions on purpose so that they can catch and handle the exception would break when suddenly no exception is raised, but I doubt there are many of those... George From mail at microcorp.co.za Fri Nov 17 03:07:13 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 17 Nov 2006 10:07:13 +0200 Subject: Secure Python References: <455c1665@quokka.wn.com.au><455c4d9b@quokka.wn.com.au> Message-ID: <035701c70a1f$64040f00$03000080@hendrik> "Stephan Kuhagen" wrote: > The problem with linux kernel limits are, that they won't work really good > on MacOSX and Windows... OTOH the idea is the right one, but the effect can > be achieved inside of Python. Since Python does byte compile the code and > the interpreter evaluates each byte code token in one evaluation step. The > interpreter could be extended for such usecases to count and limit the > number of evaluation steps allowed for untrusted script or methods in > untrusted script as well as to limit the recursion depth or memory to be > allocated. All those limits are managed by the interpreter for script code > and hence can be limited for untrusted code by the interpreter. This also > does not really make DoS impossible (what about C extensions? - maybe > restricting "import"?). - As I said before in this thread, making a sandbox > really secure is a hard job, and may need some serious changes in the > Python interpreter, but AFAIK from Tcl, it is possible - and would be nice > to have. I seem to recall previous discussion on this group about a thing called the bastion module, and that it was deprecated. Not sure if it has any relevance. - Hendrik From ask at me Mon Nov 6 21:35:29 2006 From: ask at me (alf) Date: Mon, 06 Nov 2006 20:35:29 -0600 Subject: sound process moduls in python ? In-Reply-To: References: Message-ID: fdu.xiaojf at gmail.com wrote: > Hi, > > When I was talking with my friend, I wanted to share the music I'm > listening with > my friend. I mean, I wanted my friend to hear my music and my own sound . > > I order to achieve this, I think I need to append the output of my sound > card to > the input of the sound card. > > My questions: > > 1. Is my idea possible ? > > 2. Which sound processing module is capable to do this ? The module > should at least > available at Windows platform. > > Thanks ! > > xiaojf try pymedia - there are a lot of examples From anthra.norell at vtxmail.ch Thu Nov 2 09:00:33 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Thu, 02 Nov 2006 15:00:33 +0100 Subject: SE 2.3 temporarily unavailable. Cheese shop defeats upload with erratic behavior. Urgently requesting help. Message-ID: <4549FA01.4090706@vtxmail.ch> Some time ago I had managed to upload a small package to the Cheese Shop using the data entry template. Uploading is in two steps: first the text then the package file. When I had a new version it went like this: The new text made a new page, but the new file went to the old page. The old page then had both files and all attempts at uploading the new file to the new page failed with the error message that a file could not be uploaded if it was already there. So I let it go and handed out the url of the old page, figuring that given the choice of two versions, picking the latest one was well within the capabilities of anyone. One downloader just now made me aware that the new version had misspelled extensions 'PY'. They should be lower case. So I fixed it an tried to exchange the file. One hour later I have three text pages, headed V2,2beta, V2,2beta/V2.3 and V2.3. The first (oldest) page has the old package file. The two other pages have no files. The new version package is gone, because, prior to re-uploading I was asked to delete it. The re-upload fails on all three pages with the message: 'Error processing form, invalid distribution file'. The file is a zip file made exactly the way I had made and uploaded the ones before. I am banging my real head against the proverbial wall. This thing definitely behaves erratically and I see no alternative other than to stop banging and go to the gym to take my anger out at machines and when I come back in an hour, I wish a kind, knowledgeable soul will have posted some good advice on how to vanquish such stubborn obstinacy. I have disseminated the url and the thought that someone might show up there and not find the promised goods make me really unhappy. Until such time as this upload is made, I will be happy to send SE-2.3 out off list by request. Infinite thanks Frederic From lardissone at gmail.com Wed Nov 29 11:26:51 2006 From: lardissone at gmail.com (Leandro Ardissone) Date: 29 Nov 2006 08:26:51 -0800 Subject: How to detect what type a variable is? In-Reply-To: References: <1164814586.113454.144090@l12g2000cwl.googlegroups.com> <12mragv4f1jhfb4@corp.supernews.com> Message-ID: <1164817610.856109.199870@h54g2000cwb.googlegroups.com> Thanks, I don't store Python objects in xml, but I get an object from a library that parses xml and converts it to objects. On Nov 29, 12:43 pm, Neil Cerutti wrote: > On 2006-11-29, Grant Edwards wrote: > > > On 2006-11-29, Leandro Ardissone wrote: > > >> I want to know what type is a variable. For example, I get the > >> contents of an xml but some content is a list or a string, and > >> I need to know what type it is. > > >>>> x = 'asdf' > >>>> type(x) > > > >>>> i = 0 > >>>> type(i) > >That makes me wonder how he manages to store Python objects in > xml. > > -- > Neil Cerutti From webraviteja at gmail.com Sun Nov 5 17:50:40 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 5 Nov 2006 14:50:40 -0800 Subject: Programming Language that is Spreadsheet/Table Based In-Reply-To: <1162588208.533235.266100@k70g2000cwa.googlegroups.com> References: <1162588208.533235.266100@k70g2000cwa.googlegroups.com> Message-ID: <1162767040.246506.29680@i42g2000cwa.googlegroups.com> Omar wrote: > I'm looking for a programming language or module that sorta looks and > feels like MS Excel (I love and think in tables), yet has the power and > open-endedness of python or javascript. I'm still pretty new to > python. PyCells http://pycells.pdxcb.net/ http://pycells.pdxcb.net/wiki/index.php?title=Basic_Tutorial > any ideas? i've been having some fun with VBA in excel > but I want something I can save as en exe and call my own creation, y'know? You can also do Excel automation using Python. http://www.markcarter.me.uk/computing/python/excel.html There are many packaging tools for Python. Py2exe is the most popular. Although in Excel's case, it would be difficult to make stand alone. From steve at holdenweb.com Thu Nov 2 22:28:40 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Nov 2006 03:28:40 +0000 Subject: what's the difference between these two methods? (aka, why doesn't one of them work?) In-Reply-To: <454ab2e3$0$17722$c3e8da3@news.astraweb.com> References: <1162499293.080529.5480@m73g2000cwd.googlegroups.com> <1162500604.198685.97710@i42g2000cwa.googlegroups.com> <1162501702.150119.313860@f16g2000cwb.googlegroups.com> <1162502076.438629.289560@k70g2000cwa.googlegroups.com> <1162502862.141973.324040@h48g2000cwc.googlegroups.com> <454ab2e3$0$17722$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Fredrik Lundh wrote: > >>JohnJSal wrote: >> >> >>>That's a perfectly valid comment, but in this case just not applicable. >>>I spent a lot of time working through my original question before >>>posting, but I just couldn't get it. >> >>how do you fit "a lot of time" into 18 minutes? >> >> >> > > Hmmm, I had tried to cancel sending that post but I guess it didn't > work. As I was sending it, I said to myself, "well, maybe I didn't spend > enough time before asking." > > But I guess rather than "a lot of time", I'm thinking I tried "a lot of > things," or at least all I could think of. Don't worry. It's sometimes difficult for the effbot to remember we aren't all as fearsomely intelligent as it is. I think it does a remarkably complete emulation of a human being: http://www.flickr.com/photos/30842681 at N00/152495923/ For what it's worth it's also amazingly helpful if you can ignore to sometimes acerbic wit. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Fri Nov 10 12:12:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 10 Nov 2006 18:12:55 +0100 Subject: range syntax In-Reply-To: References: Message-ID: Colin J. Williams wrote: > One of the little irritants of Python is that the range syntax is rather > long-winded: > [Dbg]>>> range(3, 20, 6) > [3, 9, 15] > [Dbg]>>> > It would be nice if one could have something like 3:20:6. if you find yourself using range a lot, maybe you should check if you couldn't use custom iterators more often. or use the R helper: >>> R[3:20:6] [3, 9, 15] >>> R[:20] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> R[0:20:2] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>> R[1:20:2] [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] where R is defined as: >>> class R: ... def __getitem__(self, slice): ... return range(*slice.indices(slice.stop)) ... >>> R = R() From mike.klaas at gmail.com Fri Nov 3 23:54:07 2006 From: mike.klaas at gmail.com (Klaas) Date: 3 Nov 2006 20:54:07 -0800 Subject: Sorted and reversed on huge dict ? In-Reply-To: <1162590153.024233.311670@b28g2000cwb.googlegroups.com> References: <1162580533.981364.211860@h54g2000cwb.googlegroups.com> <7xvelwib1b.fsf@ruckus.brouhaha.com> <1162590153.024233.311670@b28g2000cwb.googlegroups.com> Message-ID: <1162616047.891549.29550@b28g2000cwb.googlegroups.com> vd12005 at yahoo.fr wrote: > thanks for your replies :) > > so i just have tried, even if i think it will not go to the end => i > was wrong : it is around 1.400.000 entries by dict... > > but maybe if keys of dicts are not duplicated in memory it can be done > (as all dicts will have the same keys, with different (count) values)? Definitely a good strategy. The easiest way is to use intern(key) when storing the values. (This will only work if you are using 8bit strings. You'll have to maintain your own object cache if you are using unicode). I've reduced the memory requirements of very similar apps this way. -Mike From exarkun at divmod.com Fri Nov 3 21:49:26 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 3 Nov 2006 21:49:26 -0500 Subject: Physical constants In-Reply-To: <73D46C5F-12AE-4700-86D2-7FAE0DEF6C54@mac.com> Message-ID: <20061104024926.20948.1941857033.divmod.quotient.12543@ohm> On Fri, 3 Nov 2006 18:57:49 -0500, Tommy Grav wrote: >I have some code for doing orbital computations. The code is kind of >extensive with many classes, each having several functions. In these >functions I need to use constants (like the gravitational constant). >What is the best way of implementing a solution when constants are >used in several different classes and functions? I do not want to >pass the constant down through the functions. I have thought of >making a class of constants but I do not want to invoke an >instant in each function. How is the pi and e constants in math >coded? FWIW, http://twistedmatrix.com/trac/browser/sandbox/exarkun/physics/point.py Are you working on something similarly general? I'd be interested to take a look at your code if so. In my spare time I'm working on some simulation code that would probably benefit from something more correct than what's at the above URL. Jean-Paul From luismgz at gmail.com Mon Nov 6 17:26:46 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 6 Nov 2006 14:26:46 -0800 Subject: Learning Python In-Reply-To: <1162803632.788766.147590@e3g2000cwe.googlegroups.com> References: <1162803632.788766.147590@e3g2000cwe.googlegroups.com> Message-ID: <1162852006.144011.287990@k70g2000cwa.googlegroups.com> kaushal wrote: > Hi > > How do i start Learning Python,is there any reference material which I > can refer since I dont have > any programming experience > > Thanks and Regards > > Kaushal If you have no programming experience at all, I highly recomend "Non Programmers Tutorial for Python" by Josh Cogliati: http://www.honors.montana.edu/~jjc/easytut/easytut/easytut.html This is how I got my feet wet with Python, and it's very easy to follow. I also recomend "A Byte of Python" by Swaroop: http://swaroopch.info/text/Byte_of_Python:Main_Page Both ebooks are available in multiple formats and are free. God luck! Luis From bignose+hates-spam at benfinney.id.au Mon Nov 27 00:08:16 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 27 Nov 2006 16:08:16 +1100 Subject: test message References: <9fckm2p839oh7c586t93c9fn3lfppu43g3@4ax.com> <456A5A1D.60309@NOSPAMwit.edu> Message-ID: <87slg5schr.fsf@benfinney.id.au> Jordan Greenberg writes: > john.smith at nowhere.com wrote: > > This is a test message, please ignore. > > I could do that, but reminding you that test messages go in *.test > groups is way more fun. I'm betting that the test message was to the Python mailing list, not a Usenet group. Unlike for Usenet, where being able to send a message to one newsgroup is a strong indication that most others will also work, a test message to one mailing list says very little about ability to send messages to other mailing lists. -- \ "If nothing changes, everything will remain the same." -- | `\ Barne's Law | _o__) | Ben Finney From sjmachin at lexicon.net Thu Nov 30 13:42:13 2006 From: sjmachin at lexicon.net (John Machin) Date: 30 Nov 2006 10:42:13 -0800 Subject: Automatic increment In-Reply-To: References: Message-ID: <1164912133.892374.308460@f1g2000cwa.googlegroups.com> Gheorghe Postelnicu wrote: > Hi, > > I have a situation of the following type: > > for line in lineList: > for item in line.split() > myArray[counter, itemCounter] What do you imagine that the above line is doing? Alternatively, should you be posting in comp.lang.somelanguageotherthanPython ? > itemCounter = itemCounter + 1 > counter = counter +1 > > Is there a way to get rid of the manual incrementation of the 2 counters? You could have saved some wear and tear on your pinkies by doing e.g. itemCounter += 1 Cheers, John From no-spam at no-spam-no-spam.invalid Thu Nov 23 15:29:02 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 23 Nov 2006 21:29:02 +0100 Subject: python gaining popularity according to a study In-Reply-To: <1164306918.845529.95820@f16g2000cwb.googlegroups.com> References: <1164306918.845529.95820@f16g2000cwb.googlegroups.com> Message-ID: ccdetail at gmail.com wrote: > http://www.tiobe.com/index.htm?tiobe_index > > Python is the 7th most commonly used language, up from 8th. > The only one gaining ground besides VB in the top 10. > > We're glad, our app is written in python. > It's free at http://pnk.com and it is a web timesheet for project > accounting The real comparision is vs. Ruby. Seems, Ruby has won an important race because of this Rails thing. Both, the Ruby language and this thing are weak compared to Python side in almost any aspect (just better than dull LAMP). But they have managed to raise a single-minded marketing and focus. When a LAMP programmer comes to Python, there are so many different confusing things. It starts with a 'non-documented' cgi module - a 'High-Level-Interface', that cannot even iterate over the form items. A name ZOPE in focus which reveals to be a monster system with 2-year learning-curve, ready for running an article editorial system for TOP-10 newspaper companies, but unable to make simple things simple. A handful of different Djangos - choose one for each weekday and programmer ... And Ruby made it with this single-known simple URL-to-method-router (And possibly when coming from PHP & Perl one recognizes ::@$_$%??%/&... and the old namespace dirt) If there would have been a good cgi-system and a somewhat comfortable advanced URL-to-OO-router (beyond the socket wrapper HTTPServer) well exposed in the Python standard lib, the numbers would be probably very different today ... Flat Web/DB programming is one major field where programmer masses are born. The other big one is RAD-GUI/DB programming. This field is probably still wide open. Best tooled Borland RAD systems are going down meanwhile because of the stiff compiler language. Programmers look around for the next language & toolset. Python is the language - but with Python there is again a similar confusion around IDE's and GUI-libs. There is no really good IDE (but fat ones). And the major gui libs there are not Python, but are fat sickening layers upon layers upon other OO-langs. ==> VB went up. Maybe Borland should go towards a Python GUI/IDE system ... Python is probably (still) the best _language_ within that top 20 for most purposes. Richest set of libraries probably. It would be by far the best language for Web and Gui programming as well. But the Python community has missed to create focus regarding a few must-be-sharp knifes. The only area with appropriate Python success is probably sci programming. And there is 2nd-level network programming and some glueing, where Python gathers numbers mostly because of merely the superior language itself. Python is undersold und the key tools are somewhat too bloomy and fragmented for successful professional application. Robert From SSchukat at dspace.de Sat Nov 11 16:15:02 2006 From: SSchukat at dspace.de (Stefan Schukat) Date: Sat, 11 Nov 2006 22:15:02 +0100 Subject: Python opening multiple thread of matlab In-Reply-To: <1163253376.388256.146310@h54g2000cwb.googlegroups.com> Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB9023171@exchange2003.dspace.de> Hello, you just forgot to initialize the COM runtime for the separate thread. try following: def __init__(self,matlab_command): self.matlab_command = matlab_command threading.Thread.__init__(self) def run(self): import pythoncom pythoncom.CoInitialize() try: matlab_object = Dispatch('matlab.application.single') execute = getattr(matlab_object,'Execute') execute(self.matlab_command) finally: matlab_object = None pythoncom.CoUnitialize() Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org] On > Behalf Of tsjuan > Sent: Saturday, November 11, 2006 2:56 PM > To: python-list at python.org > Subject: Python opening multiple thread of matlab > > Hello Python Users, > > I've been trying to run multiple thread of Matlab by calling > its com object via python. However, I keep getting error > message that says Python can't find the attribute of certain > function that I want to execute in Matlab. > > I know the com function is exist, it works just fine if I > don't run within thread. > Below is my sample code, any helps or comments are appreciated. > > Thanks, > Tanto > > import threading > from win32com.client import Dispatch > > > class MyThread ( threading.Thread ): > > def __init__(self,matlab_command): > self.matlab_command = matlab_command > self.matlab_object = Dispatch('matlab.application.single') > threading.Thread.__init__(self) > > def run(self): > execute = getattr(self.matlab_object,'Execute') > execute(self.matlab_command) > > def awesome_dud(self): > execute = getattr(self.matlab_object,'Execute') > execute(self.matlab_command) > > > a = MyThread('a=1:1:100') > b = MyThread('b=1:1:200') > > # Running matlab function through thread (It's not working) # > ========================================================= > > a.start() > b.start() > a.join() > b.join() > > # Running matlab function not through thread (it's working) # > ========================================================= > a.awesome_dud() > b.awesome_dud() > > -- > http://mail.python.org/mailman/listinfo/python-list > From anthra.norell at vtxmail.ch Fri Nov 3 13:33:49 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Fri, 03 Nov 2006 19:33:49 +0100 Subject: ANN: SE 2.3. Available now In-Reply-To: References: <454B3B49.6070702@vtxmail.ch> <454B6FEC.20709@islandtraining.com> Message-ID: <454B8B8D.8010406@vtxmail.ch> Fredrik Lundh wrote: > Gary Herron wrote: > > >> As a matter of polite netiquette, a message like this really ought to >> have a paragraph telling us what SE *is*. (Unless it's a secret :-)) >> > > nah, if you've spent more than five minutes on c.l.python lately, you'd > noticed that it's the Solution to Everything (up there with pyparsing, I > think). > > > > And here's the proof I am being perceived as a nuisance. I apologize, keeping to myself that I don't care. Frederic From Eric_Dexter at msn.com Thu Nov 2 02:21:22 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 1 Nov 2006 23:21:22 -0800 Subject: The Python Journal In-Reply-To: <1162442611.407124.154980@e3g2000cwe.googlegroups.com> References: <1162442611.407124.154980@e3g2000cwe.googlegroups.com> Message-ID: <1162452082.061921.61530@m73g2000cwd.googlegroups.com> I think I saw one of the articles twice. It is good to see a python journal again, even better with free content. It would be good to see more 'populist' content, even transcripts of python 411 maybe. I would also like to note if they could be organised as hpp (or whatever extension the help files are) maybe spe or boa-constructor could make it easy for users to add it to there help systems. I thought I saw an internet publisher somewhere that could get you the isbn (if that is the right number) so that content could also get distributed as hard copy. https://sourceforge.net/projects/dex-tracker tleeuwenburg at gmail.com wrote: > To whom it may concern, > > I have been involved in putting together a new Python journal, called > (oh so originally) The Python Journal. This isn't related to a previous > project also called The Python Journal although we have the approval of > the group that put it together in using their name. > > http://pyjournal.cgpublisher.com is the journal URL, and it has a > number > of news feeds -- blog entries, new products (i.e. articles and volumes) > and product reviews (not used currently). > > We'd love it if you could have a look at our first issue, and let us > know what you think! > > Cheers, > -T (editor-in-chief) From scbauer at gmail.com Wed Nov 22 19:16:07 2006 From: scbauer at gmail.com (scbauer) Date: 22 Nov 2006 16:16:07 -0800 Subject: AVL Balancing In-Reply-To: <1164240291.176865.82670@l39g2000cwd.googlegroups.com> References: <1164154965.338691.327010@j44g2000cwa.googlegroups.com> <1164158188.787394.25990@b28g2000cwb.googlegroups.com> <1164240291.176865.82670@l39g2000cwd.googlegroups.com> Message-ID: <1164240967.634513.66200@b28g2000cwb.googlegroups.com> This is one of the errors that im getting Traceback (most recent call last): File "", line 1, in t.insert(5) File "/Users/stevenbauer/Desktop/AVL.py", line 68, in insert stack.append(current) NameError: global name 'stack' is not defined From tim at tdw.net Wed Nov 8 19:38:24 2006 From: tim at tdw.net (Tim Williams) Date: Thu, 9 Nov 2006 00:38:24 +0000 Subject: help using smtplib to work .. In-Reply-To: References: <1163024588.884055.12460@i42g2000cwa.googlegroups.com> <455263B5.9080704@websafe.com> <9afea2ac0611081554l56e8da5hfa4dd43c02e76a73@mail.gmail.com> <9afea2ac0611081617xa87e370se273261c76b7163c@mail.gmail.com> Message-ID: <9afea2ac0611081638x5fbbb2eep3988b12643b2af81@mail.gmail.com> On 09/11/06, Nicolas G wrote: > > > > > > Usually when sending/relaying without authentication, the From is > > irrelevant, only the To is taken into account. Maybe, GMAIL do > > something different because they have to put the mail in the sender's > > mailbox as well as the recipient's. Some ISPs will only allow a > > local FROM address though. > > > > As we're only talking about the envelope TO & FROM, you could try no > > FROM address (None or <> I forget which Smtplib needs) . > > If I left From empty I don't get any error but I still don't receive any > message. > > > The header FROM can still have the real FROM address in it, as its not > (normally) > > used during SMTP relaying. > > How you can explain that only for some address in the From field I can > receive mails' and from others I can't ? > It looks really weird to me... It must be down to how gmail's server(s) work. > Other question : Suppose I use the login procedure, the password will be > vulnerable to attacks ? If I'm right I think when no ssl is used for > authentication some one can easy see the password just by sniffing the > packets. I think the risk is low to be honest. However, smtp.gmail.com uses TLS (SSL) on ports 465 or 587. You can call STARTTLS from within smtplib. but TrevorP's TLS-lite extensions to smtplib handle it better http://trevp.net/tlslite/ :) From lycka at carmen.se Thu Nov 9 04:01:06 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 09 Nov 2006 10:01:06 +0100 Subject: Is there a commas-in-between idiom? In-Reply-To: References: Message-ID: Ernesto Garc?a Garc?a wrote: > list = [1,2,3,4,5,6] Just a nit-pick: It's considered an anti-idiom to hide builtins just as list by using it as a name for a variable. >>> list=[1,2,3,4,5] >>> tuple = (1,2,3,4,5) >>> if list == list(tuple): print "equal" ... Traceback (most recent call last): File "", line 1, in ? TypeError: 'list' object is not callable >>> #ouch! ... >>> l=list >>> del list >>> if l == list(tuple): print "equal" ... equal >>> if tuple(l)==tuple: print "equal" ... Traceback (most recent call last): File "", line 1, in ? TypeError: 'tuple' object is not callable >>> t=tuple >>> del tuple >>> if tuple(l)==t: print "equal" ... equal From gagsl-py at yahoo.com.ar Thu Nov 9 20:20:50 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 09 Nov 2006 22:20:50 -0300 Subject: object data member dumper? In-Reply-To: <4553c583$0$12165$88260bb3@free.teranews.com> References: <4550cddd$0$12104$88260bb3@free.teranews.com> <4550f442$0$20337$426a34cc@news.free.fr> <45510cc9$0$12164$88260bb3@free.teranews.com> <4553c583$0$12165$88260bb3@free.teranews.com> Message-ID: <7.0.1.0.0.20061109222013.0593b418@yahoo.com.ar> At Thursday 9/11/2006 22:16, tom arnall wrote: > > I'd suggest you instead consider a mixin object that will add recursive > > data dump functionality to any such classes you require. > >have googled a fair amount on 'mixin' but still stumped on it. Try again using "mixin class" -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From fredrik at pythonware.com Wed Nov 1 10:29:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 01 Nov 2006 16:29:07 +0100 Subject: Why can't you assign to a list in a loop without enumerate? In-Reply-To: <4qrsafFo961qU1@individual.net> References: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> <4qrln8Fo2ollU1@individual.net> <4qrsafFo961qU1@individual.net> Message-ID: Bjoern Schliessmann wrote: >> define "it". > > Sorry! I mean iterating over a list and having the list index > available in the loop. Like: > > for i, thing in enumerate(things): > pass "enumerate" is the obviously right thing for this, sure. but it's not necessarily the right thing for the OP's "I want to create a new list based on an existing list". modifying the existing list is usually not the most efficient way to do that. From irfan.habib at gmail.com Thu Nov 16 05:21:40 2006 From: irfan.habib at gmail.com (irfan.habib at gmail.com) Date: 16 Nov 2006 02:21:40 -0800 Subject: split CSV fields In-Reply-To: References: Message-ID: <1163672500.484743.6320@h54g2000cwb.googlegroups.com> s.split(','); robert wrote: > What is a most simple expression for splitting a CSV line with "-protected fields? > > s='"123","a,b,\"c\"",5.640' From rmardhani at claddaghresources.net Mon Nov 6 11:20:04 2006 From: rmardhani at claddaghresources.net (RM) Date: 6 Nov 2006 08:20:04 -0800 Subject: Full-time Python DEVELOPER needed - High-transactional environment Message-ID: <1162830004.736521.112670@k70g2000cwa.googlegroups.com> Hello Python users, We are currently looking for a PYTHON DEVELOPER in Cleveland, OH. The full-time position is with a LARGE CLIENT (situated in over 17 countries and headquartered in Cleveland) currently in a high-growth mode and is WORLD's leading Internet Content Providing firm The client offers attractive salary and great benefits, plus a creative and flexible work environment We are looking for candidates with strong OO background in Python / Java / C++ / other OO language along with backend experience If you would like to find out more about the position and/or the client, kindly give me a call at the number listed below and send me a copy of your resume for review. Thank you for your time, I look forward to hearing from you soon. Kind Regards, Rozina Mardhani Sr. Recruiter Claddagh Resources 678-405-4400 Ext. 211 rmardhani at claddaghresources.net From jblaine at mitre.org Wed Nov 1 15:39:04 2006 From: jblaine at mitre.org (Jeff Blaine) Date: Wed, 01 Nov 2006 15:39:04 -0500 Subject: CSV module, DictReader problem (bug?) Message-ID: It's been a year or so since I written Python code, so maybe I am just doing something really dumb, but... Documentation ============= class DictReader(csvfile[,fieldnames=None, [,restkey=None[, restval=None[, dialect='excel' [, *args, **kwds]]]]]) Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames. Code ==== import csv r = csv.DictReader('C:\Temp\Book1.csv') print r.next() # EOF Output ====== {'C': ':'} From jorge.vargas at gmail.com Mon Nov 13 08:45:46 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 13 Nov 2006 09:45:46 -0400 Subject: logging In-Reply-To: <1163404240.288572.38420@i42g2000cwa.googlegroups.com> References: <1163404240.288572.38420@i42g2000cwa.googlegroups.com> Message-ID: <32822fe60611130545pff483f4qd8ae0c102d6b4649@mail.gmail.com> On 12 Nov 2006 23:50:40 -0800, alain.marcel at svd-info.fr wrote: > Hi all ! > How to remove a logger ? > There si no logging.removeLogger(name) method. > I've a lot of objects that create loging. why you need a logger per object? IMO 1 per package is more then enough. > When objects are destroyed, associated logger are not. This create > memory leak... > > Thanks for any idea. > > -- > http://mail.python.org/mailman/listinfo/python-list > From nospam at domain.tld Wed Nov 8 04:31:15 2006 From: nospam at domain.tld (Stephan Kuhagen) Date: Wed, 08 Nov 2006 10:31:15 +0100 Subject: Searching for a module to generate GUI events Message-ID: Hello I'm searching for a Python Module which is able to generate GUI events on different platforms (at least X11 and Windows, MacOSX would be nice), but without being a GUI toolkit itself. So PyTk is not a choice, because I need to use it, to control GUIs of other Programs. I want to generate Mouse events (move, click etc.) and keyboard events and inject them directly into the event-queue of the underlying window system. Does somebody know such a module or do I have to utilize platform specific tools from within Python? Regards and Thanks Stephan From assaflavie at gmail.com Wed Nov 1 07:50:21 2006 From: assaflavie at gmail.com (assaf) Date: 1 Nov 2006 04:50:21 -0800 Subject: authenticated https post Message-ID: <1162385421.870142.8680@h48g2000cwc.googlegroups.com> (warning Python newbie) I'm trying to use Python to work with del.icio.us's API. Basically, I need to be able to do a simple https post, with username/password authentication. (For those interested, the del.icio.us API is here: http://del.icio.us/help/api/) I can't for the life of me find a simple https example code that works... I'm working on Windows, btw, if that makes any difference. Appreciate your help, assaf From chris.cavalaria at free.fr Thu Nov 2 10:59:56 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 02 Nov 2006 16:59:56 +0100 Subject: other ways to check for ? In-Reply-To: <4549ed5c$0$30321$426a74cc@news.free.fr> References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> <4549cf05$0$9363$426a74cc@news.free.fr> <4549ed5c$0$30321$426a74cc@news.free.fr> Message-ID: <454a15f3$0$22107$426a74cc@news.free.fr> Christophe a ?crit : > Sybren Stuvel a ?crit : >> Christophe enlightened us with: >>> I don't think it's a good idea because when you place a try catch >>> block around a function call, you'll catch any exception thrown by >>> the function itself and not only the "cannot be called" exception. >> >> That depends on the exception you're catching, doesn't it? > > And what if the function has an error and calls a non callable object ? Or even worse. Since we have : >>> None() Traceback (most recent call last): File "", line 1, in ? TypeError: 'NoneType' object is not callable >>> 1+"" Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> ""+1 Traceback (most recent call last): File "", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects All of them are TypeError exceptions. It is extremly dangerous to put a try except TypeError clause around a function call to catch the case where the function object isn't a callable :/ From bernard.chhun at gmail.com Mon Nov 6 16:56:16 2006 From: bernard.chhun at gmail.com (Bernard) Date: 6 Nov 2006 13:56:16 -0800 Subject: WebScraping In-Reply-To: <454d0fb1$0$11970$afc38c87@news.optusnet.com.au> References: <454d0fb1$0$11970$afc38c87@news.optusnet.com.au> Message-ID: <1162850176.711635.172660@m7g2000cwm.googlegroups.com> yup yup BeautifulSoup is the way to go. what would you like to scrape by the way? Graham Feeley wrote: > Can someone steer me to scripts / modules etc on webscraping please??? > Ultimately I would like someone to write a script for me. > However i am still searching for documentation on this subject > Thanks Graham From rvernica at gmail.com Wed Nov 1 19:53:01 2006 From: rvernica at gmail.com (Rares Vernica) Date: Wed, 01 Nov 2006 16:53:01 -0800 Subject: unescape HTML entities In-Reply-To: <45449EAC.4070103@vtxmail.ch> References: <45449EAC.4070103@vtxmail.ch> Message-ID: Hi, I downloades 2.2 beta, just to be sure I have the same version as you specify. (The file names are no longer funny.) Anyway, it does not seem to do as you said: In [14]: import SE In [15]: SE.version -------> SE.version() Out[15]: 'SE 2.2 beta - SEL 2.2 beta' In [16]: HTM_Decoder = SE.SE ('HTM2ISO.se') In [17]: test_string = ''' ....: ø=(xf8) # 248 f8 ....: ù=(xf9) # 249 f9 ....: ú=(xfa) # 250 fa ....: û=(xfb) # 251 fb ....: ü=(xfc) # 252 fc ....: ý=(xfd) # 253 fd ....: þ=(xfe) # 254 fe ....: é=(xe9) ....: ê=(xea) ....: ë=(xeb) ....: ì=(xec) ....: í=(xed) ....: î=(xee) ....: ï=(xef) ....: ''' In [18]: print HTM_Decoder (test_string) ø=(xf8) # 248 f8 ù=(xf9) # 249 f9 ú=(xfa) # 250 fa û=(xfb) # 251 fb ü=(xfc) # 252 fc ý=(xfd) # 253 fd þ=(xfe) # 254 fe é=(xe9) ê=(xea) ë=(xeb) ì=(xec) í=(xed) î=(xee) ï=(xef) In [19]: Thanks, Ray Frederic Rentsch wrote: > Rares Vernica wrote: >> Hi, >> >> How can I unescape HTML entities like " "? >> >> I know about xml.sax.saxutils.unescape() but it only deals with "&", >> "<", and ">". >> >> Also, I know about htmlentitydefs.entitydefs, but not only this >> dictionary is the opposite of what I need, it does not have " ". >> >> It has to be in python 2.4. >> >> Thanks a lot, >> Ray >> > One way is this: > > >>> import SE # > Download from http://cheeseshop.python.org/pypi/SE/2.2%20beta > >>> SE.SE ('HTM2ISO.se')('input_file_name', 'output_file_name') # > HTM2ISO.se is included > 'output_file_name' > > For repeated translations the SE object would be assigned to a variable: > > >>> HTM_Decoder = SE.SE ('HTM2ISO.se') > > SE objects take and return strings as well as file names which is useful > for translating string variables, doing line-by-line translations and > for interactive development or verification. A simple way to check a > substitution set is to use its definitions as test data. The following > is a section of the definition file HTM2ISO.se: > > test_string = ''' > ø=(xf8) # 248 f8 > ù=(xf9) # 249 f9 > ú=(xfa) # 250 fa > û=(xfb) # 251 fb > ü=(xfc) # 252 fc > ý=(xfd) # 253 fd > þ=(xfe) # 254 fe > é=(xe9) > ê=(xea) > ë=(xeb) > ì=(xec) > í=(xed) > î=(xee) > ï=(xef) > ''' > > >>> print HTM_Decoder (test_string) > > ?=(xf8) # 248 f8 > ?=(xf9) # 249 f9 > ?=(xfa) # 250 fa > ?=(xfb) # 251 fb > ?=(xfc) # 252 fc > ?=(xfd) # 253 fd > ?=(xfe) # 254 fe > ?=(xe9) > ?=(xea) > ?=(xeb) > ?=(xec) > ?=(xed) > ?=(xee) > ?=(xef) > > Another feature of SE is modularity. > > >>> strip_tags = ''' > ~<(.|\x0a)*?>~=(9) # one tag to one tab > ~~=(9) # one comment to one tab > | # run > "~\x0a[ \x09\x0d\x0a]*~=(x0a)" # delete empty lines > ~\t+~=(32) # one or more tabs to one space > ~\x20\t+~=(32) # one space and one or more tabs to > one space > ~\t+\x20~=(32) # one or more tab and one space to > one space > ''' > > >>> HTM_Stripper_Decoder = SE.SE (strip_tags + ' HTM2ISO.se ') # > Order doesn't matter > > If you write 'strip_tags' to a file, say 'STRIP_TAGS.se' you'd name it > together with HTM2ISO.se: > > >>> HTM_Stripper_Decoder = SE.SE ('STRIP_TAGS.se HTM2ISO.se') # > Order doesn't matter > > Or, if you have two SE objects, one for stripping tags and one for > decoding the ampersands, you can nest them like this: > > >>> test_string = "

style='line-height:110%'>René est un garçon qui > paraît plus âgé.

" > > >>> print Tag_Stripper (HTM_Decoder (test_string)) > Ren? est un gar?on qui para?t plus ?g?. > > Nesting works with file names too, because file names are returned: > > >>> Tag_Stripper (HTM_Decoder ('input_file_name'), 'output_file_name') > 'output_file_name' > > > Frederic > > > From robert.kern at gmail.com Wed Nov 1 00:46:06 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 31 Oct 2006 21:46:06 -0800 Subject: Integrating Python with Fortran In-Reply-To: <1162329971.939178.290250@m7g2000cwm.googlegroups.com> References: <1162329971.939178.290250@m7g2000cwm.googlegroups.com> Message-ID: unexpected wrote: > Hi all, > > I'm currently working on a large, legacy Fortran application. I would > like to start new development in Python (as it is mainly I/O related). > In order to do so, however, the whole project needs to be able to > compile in Fortran. > > I'm aware of resources like the F2Py Interface generator, but this only > lets me access the Fortran modules I need in Python. I'm wondering if > there's a way to generate the .o files from Python (maybe using > py2exe?) and then link the .o file with the rest of the Fortran project > using something like gcc. There are no tools specifically for embedded Python in Fortran. However, there is Elmer, which helps to create a C API for a Python library (essentially the inverse of SWIG). One can then wrap that C API with a Fortran-compliant interface in the fairly standard ways. http://elmer.sourceforge.net/ -- 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 sjdevnull at yahoo.com Thu Nov 9 00:22:42 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 8 Nov 2006 21:22:42 -0800 Subject: decorators In-Reply-To: <1163018190.510373.123020@h54g2000cwb.googlegroups.com> References: <1163018190.510373.123020@h54g2000cwb.googlegroups.com> Message-ID: <1163049762.235181.186070@f16g2000cwb.googlegroups.com> John Henry wrote: > I must be very thick. I keep reading about what decorators are and I > still don't have a good feel about it. See, for example: > > http://alex.dojotoolkit.org/?p=564 > > What exactly do I use decorators for? Metafunctions. Saying @mydecorator def foo(...): ... is just an alternative way of writing: def foo(...): ... foo = mydecorator(foo) From horpner at yahoo.com Fri Nov 10 09:54:58 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Nov 2006 15:54:58 +0100 Subject: Py3K idea: why not drop the colon? References: <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <45538b0d$0$26485$c3e8da3@news.astraweb.com> Message-ID: On 2006-11-10, skip at pobox.com wrote: > > Neil> The colon's main purpose seems to be to allow one-liners: > > Neil> Easy to parse: if a < b: a += 1 > Neil> Hard to parse if a < b a += 1 > > No, as the note from Tim Peters referenced by Robert Kern > pointed out earlier in this thread, the ABC language designers > found that indentation-based block structure by itself wasn't > enough to clue new users in about the code structure. Adding > the colon at the end of the if/while/for clause helped. Thanks. I worded that lousily. -- Neil Cerutti The Minutemen are not tall in terms of height. --Dan Bonner From environ314 at gmail.com Sun Nov 26 03:32:53 2006 From: environ314 at gmail.com (Dan) Date: 26 Nov 2006 00:32:53 -0800 Subject: utf - string translation In-Reply-To: <1164232741.215312.322990@k70g2000cwa.googlegroups.com> References: <1164224962.711265.198090@h48g2000cwc.googlegroups.com> <1164226304.119425.206380@h54g2000cwb.googlegroups.com> <1164232741.215312.322990@k70g2000cwa.googlegroups.com> Message-ID: <1164529973.299095.155940@n67g2000cwd.googlegroups.com> On 22 nov, 22:59, "John Machin" wrote: > > processes (Vigen?re) > So why do you want to strip off accents? The history of communication > has several examples of significant difference in meaning caused by > minute differences in punctuation or accents including one of which you > may have heard: a will that could be read (in part) as either "a chacun > d'eux million francs" or "a chacun deux million francs" with the > remainder to a 3rd party. > of course. My purpose is not doing something realistic on a cryptographic view. It's for learning rudiments of programming. In fact, coding characters is a kind of cryptography I mean, sometimes, when friends can't read an email because of the characters used... I wanted to strip off accents because I use the frequences of the charactacters. If I only have 26 char, it's more easy to analyse (the text can be shorter for example) From chris.cavalaria at free.fr Wed Nov 15 04:08:17 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 15 Nov 2006 10:08:17 +0100 Subject: Py3K idea: why not drop the colon? In-Reply-To: <1163537964.142102.327540@m7g2000cwm.googlegroups.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163315927.963179.114030@m73g2000cwd.googlegroups.com> <1163353941.3497.45.camel@localhost.localdomain> <4558BE80.9010909@hobbshouse.org> <1163466041.196606.254700@i42g2000cwa.googlegroups.com> <1163537964.142102.327540@m7g2000cwm.googlegroups.com> Message-ID: <455ad90a$0$11689$426a74cc@news.free.fr> Stephen Eilert a ?crit : > Well, I *hate* underscores with a passion. So it is kinda frustrating > that I *have* to say "__init__". The fact that the coding conventions > for Python suggest things such as methods_called_this_or_that do not > help. Everything else seems fine, since if there's voodoo involved, it > had best be sticking out from the text in big, bloody, blinking, red > letters. > > I know, there's noone preventing me from doing otherwise (except for > that blasted __init__). I'd like to follow the pack here, tho. I'm sure a carefully crafted metaclass can be used to automaticaly convert any init function to __init__ ;) From george.sakkis at gmail.com Wed Nov 1 09:33:52 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 1 Nov 2006 06:33:52 -0800 Subject: High level csv reader References: <1162361464.706313.221590@e64g2000cwd.googlegroups.com> Message-ID: <1162391632.405631.131640@e3g2000cwe.googlegroups.com> skip at pobox.com wrote: > George> It occured to me that most times I read a csv file, I'm often > George> doing from scratch things like assigning labels to columns, > George> mapping fields to the appropriate type, ignoring some fields, > George> changing their order, etc. Before I go on and reinvent the > George> wheel, is there a generic high level wrapper around csv.reader > George> that does all this ? > > I'm not aware of anything that specifically addresses these ideas. Here are > some thoughts though: > > * If you use the DictReader class you can ignore fields you aren't > interested in more easily since you access the fields of interest by > name and with the fieldnames parameter to the constructor can assign > column names to csv data which lacks it (use similar functionality in > DictWriter to create column labels on output). You can also specify > the restkey parameter to the constructor and thus only specify the > fields of interest in the fieldnames parameter. (I think. I've never > actually used that capability, but that's what the documentation > suggests.) > > * There was a thread earlier this month with this subject: > > paseline(my favorite simple script): does something similar exist? > > Check it out for a number of different solutions to formatting the > fields in a line of text. The idea can easily be extended to a list > or dict of values instead, perhaps in a subclass of DictReader. > > Skip Indeed, they are both relevant; actually Fredrik's suggestion in that thread was my starting point. Here's my my current API for the (most typical) case of fixed-size rows, addressing my most common requirement, field conversions (no named columns for now): http://rafb.net/paste/results/4UgvSD50.html. It looks somewhat involved but it's more along the lines of "making easy things easy and hard things possible". Comments and suggestions are most welcome. George From cbarbez at gmail.com Fri Nov 10 06:30:04 2006 From: cbarbez at gmail.com (DarkPearl) Date: 10 Nov 2006 03:30:04 -0800 Subject: windows service with SNMP In-Reply-To: <1163157344.987173.259940@i42g2000cwa.googlegroups.com> References: <1163157344.987173.259940@i42g2000cwa.googlegroups.com> Message-ID: <1163158204.221538.254310@h48g2000cwc.googlegroups.com> Sorry for language, i wanted post in FR.comp.lang.python. But... hello with all, after having to create a Windows service with py2exe, I have this problem when I launch the service: here what I find in the eventLog: The instance's SvcRun() method failed : (-2147221020, 'Syntaxe incorrecte', None, None) I don't find a the problem. If you can help me, thank's From comp.ogz at gmail.com Wed Nov 1 16:40:21 2006 From: comp.ogz at gmail.com (=?utf-8?q?O=C4=9Fuz_Yar=C4=B1mtepe?=) Date: Wed, 1 Nov 2006 23:40:21 +0200 Subject: jyton usage in a python program Message-ID: <200611012340.21801.comp.ogz@gmail.com> Hi all. I am planning to develop an application using Python. I will need to use Zemberek libraries that are written with Java. I know i can use Java libraries with the help of Jython. I will write my software by Python and will use some modules inside it. But i will need to use that Java libraries also inside my Python program. I don't know how! I will need to import that libraries and use some of their methods and check the return values during the flow of the python program. How can i write jython codes inside my Python program? With my best wishes. -- O?uz Yar?mtepe http://www.yarimtepe.com From horpner at yahoo.com Wed Nov 1 09:29:03 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 1 Nov 2006 15:29:03 +0100 Subject: Style for modules with lots of constants Message-ID: The Glk API (which I'm implementing in native Python code) defines 120 or so constants that users must use. The constants already have fairly long names, e.g., gestalt_Version, evtype_Timer, keycode_PageDown. Calls to Glk functions are thus ugly and tedious. scriptref = glk.fileref_create_by_prompt( glk.fileusage_Transcript | glk.fileusage_TextMode, glk.filemode_WriteAppend, 0) Please give me some good style advice for this situation. I know some modules are designed to be used as 'from XXX import *'. Since the Glk API is heavily influenced by its inception in C this might not be a huge problem. All the functions in the API have glk_ prepended, since C has no namespaces. I think it makes sense to stick the glk_'s back on the functions and instruct users to 'from Glk import *', but I know it doesn't conform with Python practice, and Python has plenty of modules that were originally designed in C, but don't insist on polluting the global namespace. Would it better to use strings instead? Some Python builtins use them as a way to avoid creating of global constants. scriptref = glk.fileref_create_by_prompt('Transcript+TextMode', 'WriteAppend', 0) Parsing the combinable bitfield contants might be slowish, though. Thanks for taking the time to consider my question. -- Neil Cerutti For those of you who have children and don't know it, we have a nursery downstairs. --Church Bulletin Blooper From no-spam at no-spam-no-spam.invalid Fri Nov 3 08:50:24 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 03 Nov 2006 14:50:24 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> Message-ID: Filip Wasilewski wrote: > robert wrote: >> I'd like to use multiple CPU cores for selected time consuming Python computations (incl. numpy/scipy) in a frictionless manner. >> >> Interprocess communication is tedious and out of question, so I thought about simply using a more Python interpreter instances (Py_NewInterpreter) with extra GIL in the same process. >> I expect to be able to directly push around Python Object-Trees between the 2 (or more) interpreters by doing some careful locking. > > I don't want to discourage you but what about reference counting/memory > management for shared objects? Doesn't seem fun for me. in combination with some simple locking (anyway necessary) I don't see a problem in ref-counting. If at least any interpreter branch has a pointer to the (root) object in question the ref-count is >0. ---- Question Besides: do concurrent INC/DEC machine OP-commands execute atomically on Multi-Cores as they do in Single-Core threads? Example: obj=Obj() In a read-only phase (e.g. after computations) without locking, 2 Interpreters would for example both access the obj (and change around the refcount but no data). The CPU will execute 2 [INC/DEC @refcount] OP-codes on different cores concurrently. Is it guaranteed that the counts sum up correctly? > Take a look at IPython1 and it's parallel computing capabilities [1, > 2]. It is designed to run on multiple systems or a single system with > multiple CPU/multi-core. It's worker interpreters (engines) are loosely > coupled and can utilize several MPI modules, so there is no low-level > messing with GIL. Although it is work in progress it already looks > quite awesome. > > [1] http://ipython.scipy.org/moin/Parallel_Computing > [2] http://ipython.scipy.org/moin/Parallel_Computing/Tutorial there are some MPI methods around. (This IPython method seems to be only on the level of an artefact of the interactive terminal connections.) Yet with its burden of expensive data sync thats far away from my requirements. Thats for massive parallel computing and in sci areas. I do selected things with interprocess shared memory techniques already. Thats medium efficent. Multiple interpreters inside one process seem to be most promising for seemless multi-core programming. As all Python objects share the same malloc space - thats the key requirement in order to get the main effect. As soon as with have object pickling in between its well away from this very discussion. robert From stefan.behnel-n05pAM at web.de Wed Nov 22 08:20:26 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 22 Nov 2006 14:20:26 +0100 Subject: XML Validation in Python using XSV In-Reply-To: <1164200431.878328.175100@f16g2000cwb.googlegroups.com> References: <1164200431.878328.175100@f16g2000cwb.googlegroups.com> Message-ID: <45644E9A.3030209@web.de> bmichel at gmail.com wrote: > I'd like to use XSV for validating an XML file in Python. > I am working on Linux Debian platform. > I'm not sure how to install XSV and how to configure it. My goal is to > be able to import the XSV library in Python and be able to use it's > functions. You can use "dpkg" to install the .deb. Read "man dpkg". BTW: any reason you need to use XSV? There are some other libraries out there that can validate XML based on XML Schema and RelaxNG, e.g. lxml. They are much more powerful than XSV. Stefan From webmaster at cacradicalgrace.org Mon Nov 27 14:41:29 2006 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Mon, 27 Nov 2006 12:41:29 -0700 Subject: case insensitive dictionary References: <1164494606.514366.124810@l39g2000cwd.googlegroups.com> Message-ID: John Henry wrote: > print pets.keys() > > should print: > > "Cat", "Dog" If you do: Py> pets['Cat'] = 2 Py> pets['Dog'] = 3 Py> pets['DOG'] = 4 Py> pets['cat'] += 5 Py> pets.keys() What should the result be? "['Cat', 'Dog']" or "['cat', 'DOG']"? That is to say, if you use a new case in redefining the values of your case insensitive dictionary, does the key take on the new case, or will it always and forever be the case originally given to it? Cheers, Cliff From anthra.norell at vtxmail.ch Wed Nov 1 12:48:44 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Wed, 01 Nov 2006 18:48:44 +0100 Subject: Where do nested functions live? In-Reply-To: References: Message-ID: <4548DDFC.9020409@vtxmail.ch> Rob Williscroft wrote: > Frederic Rentsch wrote in news:mailman.1556.1162316571.11739.python- > list at python.org in comp.lang.python: > > >> Rob Williscroft wrote: >> >>> Frederic Rentsch wrote in news:mailman.1536.1162292996.11739.python- >>> >>>> Rob Williscroft wrote: >>>> >>>>> Frederic Rentsch wrote in news:mailman.1428.1162113628.11739.python- >>>>> > > [snip] > > >>>>> >>>>> >>>> Here I'm lost. What's the advantage of this? It looks more convoluted. >>>> >>>> >>> I'll agree that having to explicitly define a namespace class first >>> does add some convolution. >>> >>> But if you refer to having to prefix you "outer" variables with >>> "scope." then this would be the same as claiming that the explict use >>> of self is convoluted, which is a valid opinion, so fair enough, but >>> I can't say that I agree. >>> >>> >>> >> I didn't mean to call into question. I didn't understand the advantage >> of the added complexity of your second example over the first. >> >> > > Ok, I missed your point, as for the second example it was an attempt > to show that further refactoring from a function with local functions > that are sharing some state via the scope object, to a class with > methods that share state via the instance, is a matter of editing > a few lines. > > This is useful when a function grows too large (for some value of > "too large"). As an added bonus you get to use the same thechniques > with both styles of coding. > > [snip] > > Rob. > Rob, Thanks a lot for your input. I'll have to digest that. Another question I had and forgot was this: Since we have a class that goes out of scope when the function returns, and we don't need more than one instance, why bother to make an instance? Why not use the class object itself? def whatever( new_ms ): class scope ( object ): def inner(): scope.mseconds = new_ms - s * 1000 m, scope.seconds = divmod (s, 60) h, scope.minutes = divmod (m, 60) d, scope.hours = divmod (h, 24) scope.weeks, scope.days = divmod (d, 7) Frederic From casevh at comcast.net Mon Nov 6 08:34:16 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 6 Nov 2006 05:34:16 -0800 Subject: Building C extensions In-Reply-To: References: Message-ID: <1162820056.767020.261250@m73g2000cwd.googlegroups.com> Paolo Pantaleo wrote: > Well I'm just courious: if I want to buid a C extension, I shoul use > the same compiler that has been used to build python (right?). Since > python has been built using Visual C, how can I build an extension if > I don't have Visual Studio? > > PAolo Use mingw32. It should work fine for most extensions. For example, see http://groups.google.com/group/comp.lang.python/msg/8e2260fe4d4b7de9 and the followup messages. casevh From ptmcg at austin.rr._bogus_.com Wed Nov 1 18:29:36 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 01 Nov 2006 23:29:36 GMT Subject: 3d programming without opengl References: <1162410125.954506.122630@b28g2000cwb.googlegroups.com> Message-ID: "Jordan" wrote in message news:1162410125.954506.122630 at b28g2000cwb.googlegroups.com... > On > the other hand, I thought that you were looking for something that > doesn't use openGL and I think that Slut is built around it. > Yes, slut *does* use OpenGL, so if that is in fact a poison pill for this app, it's a no-go. The only reason I posted my original pointer to is was to show that an OpenGL app doesn't require using a complicated API. -- Paul From cgseymour at gmail.com Wed Nov 1 17:20:28 2006 From: cgseymour at gmail.com (Chris Seymour) Date: 1 Nov 2006 14:20:28 -0800 Subject: ANN: SPE 0.8.3.c Python IDE editor In-Reply-To: <1162395086.009206.45020@f16g2000cwb.googlegroups.com> References: <1162206008.469787.270830@m73g2000cwd.googlegroups.com> <1162213852.270705.275740@b28g2000cwb.googlegroups.com> <1162234468.199971.134690@m7g2000cwm.googlegroups.com> <1162395086.009206.45020@f16g2000cwb.googlegroups.com> Message-ID: <1162419627.947599.285670@f16g2000cwb.googlegroups.com> Hi Stani, I got it going now. Not sure why but seems good to go now. Thanks for a great product. Cheers. Chris SPE - Stani's Python Editor wrote: > I checked the berlios site and it seems to be working. Or do you have > another problem? > Stani > > Chris Seymour schreef: > > > Hi Stani, > > Not able to reach Berlios. The SourceForge page does not have the > > Windows installer. Any ideas when it will be available? > > > > Thanks. > > > > Chris > > Bernard wrote: > > > thanks Stani! > > > > > > SPE - Stani's Python Editor wrote: > > > > This is a maintenance release (mostly bug fixing) to prove that SPE is > > > > alive and well! In case you are using wxPython2.7 you'll need to > > > > upgrade to this release. Submitted patches will be reviewed and > > > > included if approved for next release. Thanks for all your patient > > > > support and continuing donations. > > > > > > > > The SPE 0.8.2.a release got downloaded 110550 times on berlios and > > > > sourceforge together. Not bad. This means SPE has not seen an update > > > > for a while or is getting very popular. Maybe both ;-) > > > > > > > > Installers are available for python 2.3, 2.4 and 2.5 for Windows and as > > > > a rpm including wxPython. Other operating systems can choose the > > > > no-setup.zip or targ.gz archives. A .deb archive is being prepared for > > > > Debian Linux systems such as Ubuntu. > > > > > > > > wxGlade is unfortunately not compatible with wxPython2.7. So if you > > > > want to use, you'll need wxPython2.6. > > > > > > > > :**Fixes**: > > > > > > > > - output is now done with a fixed font > > > > - uml.py is now again a stand alone demo > > > > - upgraded and fixed wxGlade > > > > - fixed for wxPython2.7 (and still backwards compatible with > > > > wxPython2.6) > > > > - updated NotebookCtrl > > > > > > > > :**Contributors**: > > > > > > > > - Andrea Gavana (NoteBookCtrl) > > > > - Alberto Griggio (wxGlade) > > > > - Michael Foord (python 2.3 + 2.5 releases for windows) > > > > > > > > :**Donations**: > > > > > > > > The development of SPE is driven by donations. Each of these donors > > > > receives the pdf manual in thanks for their support of SPE. > > > > > > > > - James Carroll (60 euro) > > > > - John DeRosa (50 euro) > > > > - Fumph LLC (50 euro) > > > > - Ronald Britton (40 euro) > > > > - David Downes (40 euro) > > > > - Jorge Carrillo (40 euro) > > > > - Nicolas Berney (40 euro) > > > > - Francois Schnell (30 euro) > > > > - Olivier Cortes (30 euro) > > > > - Ayrshire Business Consulting Limited (30 euro) > > > > - Chris White (25 euro) > > > > - Thomas Wengerek (20 euro) > > > > - John Rudolph (20 euro) > > > > - Michael O'Keefe (20 euro) > > > > - Michael Brickenstein (20 euro) > > > > - Richard Walkington (20 euro) > > > > - Oliver Tomic (20 euro) > > > > - Jose Maria Cortes Arnal (20 euro) > > > > - Jeffrey Emminger (20 euro) > > > > - Eric Pederson (20 $) > > > > - Charles Bosson (15 euro) > > > > - Angelo Caruso (15 euro) > > > > - Chris Hengge (15 $) > > > > - Loïc Allys (15 euro) > > > > - Marcin Chojnowski (15 euro) > > > > - Boris Krasnoiarov (15 euro) > > > > - Paul Furber (15 euro) > > > > - Gary Robson (15 euro) > > > > - Ralf Wieseler (15 euro) > > > > - Samuel Schulenburg (10 euro) > > > > - Leland Hulbert II (10 euro) > > > > - Javier De La Mata Viader (10 euro) > > > > - Dorman Musical Instruments (10 euro) > > > > - Jaroslaw Sliwinski (10 euro) > > > > - Alessandro Patelli (10 euro) > > > > - James Pretorius (10 euro) > > > > - Richard Wayne Garganta (10 euro) > > > > - Maurizio Bracchitta (10 euro) > > > > - Larry Lynch (10 euro) > > > > - Kay Fricke (10 euro) > > > > - Henrik Binggl (10 euro) > > > > - Jerol Harrington (10 euro) > > > > - Victor Adan (10 euro) > > > > - James Fuqua (10 euro) > > > > - Christian Seberino (5 euro) > > > > - Serge Smeesters (5 euro) > > > > - Jarek Libert (5 euro) > > > > - Robin Friedrich (5 euro) > > > > - Udo Rabe (5 euro) > > > > - Roch Leduc (4 euro) > > > > - Rha Diseno y Desarrollo (2 euro) > > > > > > > > :**Installation**: > > > > > > > > - See http://pythonide.stani.be/manual/html/manual2.html > > > > > > > > :**Development**: > > > > > > > > - http://developer.berlios.de/mail/?group_id=4161 > > > > > > > > About SPE: > > > > SPE is a python IDE with auto-indentation, auto completion, call tips, > > > > syntax coloring, uml viewer, syntax highlighting, class explorer, > > > > source index, auto todo list, sticky notes, integrated pycrust shell, > > > > python file browser, recent file browser, drag&drop, context help, ... > > > > Special is its blender support with a blender 3d object browser and its > > > > ability to run interactively inside blender. Spe integrates with XRCed > > > > (gui > > > > designer) and ships with wxGlade (gui designer), PyChecker (source > > > > code doctor), Kiki (regular expression console) and WinPdb (remote, > > > > multi-threaded debugger). > > > > > > > > The development of SPE is driven by its donations. Anyone who donates > > > > can ask for an nice pdf version of the manual without ads (74 pages). From george.sakkis at gmail.com Sun Nov 19 23:38:58 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 19 Nov 2006 20:38:58 -0800 Subject: a few extensions for the itertools References: <4560bfb0$0$10578$3b214f66@tunews.univie.ac.at> Message-ID: <1163997538.085630.102190@m73g2000cwd.googlegroups.com> Steven D'Aprano wrote: > > A short description to all the functions: > > > > icmp(iterable1, iterable2) -> integer > > Return negative if iterable1 < iterable2, > > zero if iterable1 == iterable1, > > positive if iterable1 > iterable1. > > > What does it mean for an iterable to be less than another iterable? That > it has fewer items? How do these two iterables compare? > > iter([1, 2, None, "foo", 3+2j]) > > def ones(): > while 1: > yield 1 > > Which is smaller? Haven't checked the specific implementation, but I would expect it to behave like sequences of the same type, i.e. first compare the first elements of the iterables; if they are equal compare the second elements, and so on, until the first inequality or until the shorter one ends. In your example, the second iterable is smaller. Needless to say, you'd better not compare an infinite iterable with itself ;-) > > drop(n,iterable) -> iterable > > drops the first n elemetns of iterable and > > return a iterator over the rest > > Just like itertools.islice(iterable, n, None) > > >>> list(itertools.islice(xrange(20), 15, None)) > [15, 16, 17, 18, 19] > > (Aside: I think islice would be so much cleaner if it took keyword > arguments.) How about slice notation ? I just posted in the Cookbook an OO wrapper of itertools that, among other functions, uses slice notation for islice and "+" for chain. Admittedly, my proposal in the py-3k list to make iter() return itertools-enabled iterators was overwhelmingly shot down, but I still like it anyway. FWIW, here's the Cookbook link: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498272 George From p.lavarre at ieee.org Fri Nov 10 00:35:47 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 9 Nov 2006 21:35:47 -0800 Subject: how is python not the same as java? References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> Message-ID: <1163136947.735028.95160@m73g2000cwd.googlegroups.com> Jython exists. From python.list at tim.thechases.com Thu Nov 16 11:53:17 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 16 Nov 2006 10:53:17 -0600 Subject: Yield In-Reply-To: References: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> <455b4f9f$1@usenet01.boi.hp.com> <1163659530.752607.120880@m73g2000cwd.googlegroups.com> <455c15ca$1@news.eftel.com> <455c1ddf@news.eftel.com> <1163691173.737911.130410@i42g2000cwa.googlegroups.com> <1163693354.446751.38890@b28g2000cwb.googlegroups.com> Message-ID: <455C977D.2070009@tim.thechases.com> >> I absoultely agree. Thanks for pointing me out to some real-world >> code. However, the function you pointed me to is not a generator >> (there is no yield statement... it just returns the entire list of >> primes). > > Oops, should have looked at the code more closely. Another example > would be os.walk() in the standard library. I've used a similar scheme for dealing with incoming data files. Sometimes, I get them Emailed/FTP'ed so they're sitting in a folder, so I can do a multitude of them by just pointing os.walk() at them. Other times, I get them on specially formatted CDs. It's nice to have the clean main-loop logic of: for file_name in source: do_stuff(file_name) and be able to dynamically set "source" to an generator that either wraps os.walk() for a given directory or repeatedly (1) reads the file on the CD to know where it should be dumped, (2) copies files off the CD to their associated dumping ground, (3) ejects the CD, (4) yields the name of the file to process in the dumping-ground directory, and (5) prompts the user if there are more CDs to be processed. Without "yield" functionality, I'd either have to have two duplicate loops with similar internal logic (the do_stuff() sort of code), or I'd have to read in all the files off the CD and *then* process them all as a list afterwards. Just one of the places I've recently been thankful for generators. -tkc From fredrik at pythonware.com Wed Nov 1 15:34:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 01 Nov 2006 21:34:52 +0100 Subject: scared about refrences... In-Reply-To: <1162412436.595926.66940@i42g2000cwa.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162251429.386255.289620@e3g2000cwe.googlegroups.com> <4547d0d7$0$7246$426a34cc@news.free.fr> <1162412436.595926.66940@i42g2000cwa.googlegroups.com> Message-ID: SpreadTooThin wrote: >> Plain wrong. There's no "primitives" (ie : primitive data types) in >> Python, only objects. And they all get passed the same way. > > so.. > def fn(x): > x = x + 1 > print x > > a = 2 > fn(a) > fn(2) > > Wouldn't you say that this is being passed by value rather than by > refrence? Python uses neither "call by value" nor "call by reference", but that's irrelevant: the result you're seeing has nothing to do with the calling model, but with how assignment works. Gabriel already posted this link; I suggest you read it again: http://www.effbot.org/zone/python-objects.htm From pavlovevidence at gmail.com Wed Nov 15 19:28:20 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 15 Nov 2006 16:28:20 -0800 Subject: Python v PHP: fair comparison? References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163605597.576368.243640@f16g2000cwb.googlegroups.com> Message-ID: <1163636900.165072.55310@k70g2000cwa.googlegroups.com> walterbyrd wrote: > Trying to be as fair as I can be, my research shows that demand for > developers where PHP is the primary is *far* higher than jobs where > Python is the primary skills. Probably because PHP is so bug-prone and man-inefficient that a small website occupies a programmer's whole time, whereas a single Python (or Ruby, or Perl, or even Java) programmer could manage several web sites. (If by "probable" I mean "wishful thinking", that is :) Carl Banks From paddy3118 at netscape.net Sun Nov 19 23:51:29 2006 From: paddy3118 at netscape.net (Paddy) Date: 19 Nov 2006 20:51:29 -0800 Subject: basic python questions References: <1163829271.660193.70450@j44g2000cwa.googlegroups.com> <1163868656.416276.277310@m7g2000cwm.googlegroups.com> <4s8u91Fumc9aU1@mid.uni-berlin.de> <4560dc49$0$10440$426a74cc@news.free.fr> Message-ID: <1163998289.608597.115010@h48g2000cwc.googlegroups.com> Bruno Desthuilliers wrote: > And this would be still more informative (and not deprecated...): > > filename = '/tmp/foo' > f = open(fliename) > > Catching an exception just to raise a less informative one is somewhat > useless IMHO. Except that in the 'artificial' environment of homework, you are marked for what you *show* you know, Catching an exception shows that the pupil considered that opening a file could throw an exception. You would have to comment that a try except block was considered, give an example of correct usage, then why it was not used, to get equivalent, (or slightly higher), marks. (That was drilled into me so many times at school). - Paddy. From johnjsal at NOSPAMgmail.com Tue Nov 14 16:52:43 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 14 Nov 2006 16:52:43 -0500 Subject: refactoring so that multiple changes can be made with one variable? In-Reply-To: <1163522075.704650.40850@i42g2000cwa.googlegroups.com> References: <4559e396$0$32430$c3e8da3@news.astraweb.com> <1163522075.704650.40850@i42g2000cwa.googlegroups.com> Message-ID: <455a3a7f$0$32421$c3e8da3@news.astraweb.com> Paddy wrote: > You could keep a handle on all object instances created then go through > the objects making appropriate changes, e.g: > > > class Character(object): > instances = [] > def __init__(self, name, strength, dexterity, intelligence): > instances.append(self) > # as before ... > def mod_instances(self): > for inst in instances: > inst.some_property += 1 # or whatever > # (Untested) But doesn't this require that the change be predetermined so you can code it into the method? I don't necessarily need a programmatic way to do this, just a simple way to go back to the code and edit a single thing, instead of having to update all the numbers. From george.sakkis at gmail.com Fri Nov 10 01:14:50 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 9 Nov 2006 22:14:50 -0800 Subject: how is python not the same as java? References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> Message-ID: <1163139290.594834.240860@h48g2000cwc.googlegroups.com> how are BMWs not the same with Yugos ? both have four wheels and burn gasoline................. From grahamd at dscpl.com.au Tue Nov 7 18:38:51 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 7 Nov 2006 15:38:51 -0800 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? References: Message-ID: <1162942731.611376.128350@i42g2000cwa.googlegroups.com> Shane Hathaway wrote: > robert wrote: > > I'd like to use multiple CPU cores for selected time consuming Python > > computations (incl. numpy/scipy) in a frictionless manner. > > > > Interprocess communication is tedious and out of question, so I > > thought about simply using a more Python interpreter instances > > (Py_NewInterpreter) with extra GIL in the same process. I expect to > > be able to directly push around Python Object-Trees between the 2 (or > > more) interpreters by doing some careful locking. > > > > Any hope to come through? If possible, what are the main dangers? Is > > there an example / guideline around for that task? - using ctypes or > > so. > > > > Or is there even a ready made Python module which makes it easy to > > setup and deal with extra Interpreter instances? If not, would it be > > an idea to create such thing in the Python std libs to make Python > > multi-processor-ready. I guess Python will always have a GIL - > > otherwise it would loose lots of comfort in threaded programming > > I'd like to mention mod_python, which creates multiple interpreters > inside Apache. It does this transparently and works well. There is no > apparent lock contention between the interpreters, because no Python > objects are shared. In relation to mod_python, your statement isn't strictly true. One can create scenarios in mod_python where a Python object created in the context of one interpreter is then used in another interpreter at a later point. Generally this isn't an issue because it is part of a recursive sequence of processing and thus while the second interpreter is doing stuff with the object the first is stalled waiting for the second to return. It wouldn't be totally inconceivable though for a user to create threads which may operate on the object at the same time in the first interpreter as the object is being used in the second interpreter. The situation gets even more complicated when you start to use third party modules which may be used from multiple interpreters and a multithreaded Apache MPM is used and where the third party module performs callbacks into interpreters with some common object. Thus, mod_python may not be able to benefit from each Python interpreter instance having its own GIL if that was your point in referencing mod_python. Graham From rtw at freenet.co.uk Wed Nov 1 15:52:40 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Wed, 01 Nov 2006 14:52:40 -0600 Subject: Style for modules with lots of constants References: Message-ID: Tim Chase wrote in news:mailman.1617.1162412498.11739.python- list at python.org in comp.lang.python: >>> The reason I used instances instead of just the Constants >>> class was so that I could define a little more descriptive >>> context for the constants, >> >> Sorry I don't know what you mean here, could I have an example > > > It helps in the recognition if you have separation between > something like > > turnDirection.LEFT class turnDirection( object ) : pass turnDirection.LEFT = 0 turnDirection.RIGHT = 1 > > and > > alignment.LEFT class alignment( object ) : pass alignment.LEFT = 3 > > They may be the same or different value for LEFT, but by grouping > them in a "descriptive context", it's easy to catch mistakes such as > > paragraph.align(turnDirection.LEFT) > > when what you want is > > paragraph.align(alignment.LEFT) > > and, as an added bonus, prevents name clashes such as > > turnDirection.LEFT = 2 > alignment.LEFT = 0 > > With the grab-bag o' constants, you have to use old-school > C-style in your modern name-space'd Python: > > gboc.TURN_LEFT = 2 > gboc.ALIGN_LEFT = 0 > > or even worse, you'd end up with cruftage where you have > > gboc.LEFT = 2 > gboc.ALIGN_LEFT = 0 #created a month later as needed > > and then accidentally call > > paragraph.align(gboc.LEFT) > > when you mean > > paragraph.align(gboc.ALIGN_LEFT) > > This is what I understand the grandparent's post to be referring > to by "descriptive context". Fair enough, but there is nothing in this that can't be done with pure (instance free) classes as shown above, with the advantage that the client just imports the name for the set of constants they want to use, and uses them with no need to construct. Rob. -- http://www.victim-prime.dsl.pipex.com/ From steve at holdenweb.com Wed Nov 8 11:53:08 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Nov 2006 10:53:08 -0600 Subject: Python Error:IndentationError: expected an indented block In-Reply-To: <20061108154702.61516.qmail@web58107.mail.re3.yahoo.com> References: <20061108154702.61516.qmail@web58107.mail.re3.yahoo.com> Message-ID: Antonios Katsikadamos wrote: > hi all. I try to run an old python code and i get the following message > > File "/home/antonis/db/access.py", line 119 > def DoCsubnet1 (action, subject, target, args): # DoC > servers net > ^ > IndentationError: expected an indented block > > 1) and I don't know what causes it. I would be grate full if you could > give me a tip. > Typically you have a line ending in a colon (like an "if" or "for" statement) where the next line isn't at a higher indented level. This is an indication that the code NEVER worked. > 2) how can i overcome it? Can i use the keyword pass?and if how ccan i > use it > You could just blindly add an indented pass statement, but there is of course no guarantee this will be what you require. How long is the code? Would it be practical to publish it here? (If it's more than 200 lines assume the answer to that last question is "no"). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From e0427417 at student.tuwien.ac.at Mon Nov 20 22:10:38 2006 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Tue, 21 Nov 2006 04:10:38 +0100 Subject: Help!!! New to Python and getting an error I can't figure out In-Reply-To: References: Message-ID: <45626dcc$0$8024$3b214f66@tunews.univie.ac.at> Tom Mountney wrote: > Any help is greatly appreciated!!! > > I'm learning python and from a book I tried this program: (all the > indentation is there just doen't appear in this EMail) > ---------------------------------------------------------- > > #file grep.py > import os > from os import isfile > > class dirGrep: > def __init__(self, directory): > self.files = filter(isfile, > [os.path.join(directory, x) for x in os.listdir(directory)]) > > def findLines(self, pattern, filelist=none): > """Accepts pattern, returns lines that contain pattern. > Optional 2nd argument is a filelist to search""" > if not filelist: > filelist = self.files > results = [] > for file in filelist: > fo = open(file) > results += [x for x in fo.readlines() > if x.find(pattern) != -1] > fo.close() #explicit close of the file object > return results > > def findfiles(self, pattern): > "Accepts pattern, returns filenames that contain pattern" > return[x for x in self.files if x.find(pattern) != -1 Missing ']' !!!! [ ... ] can span over multiple lines, so python reads until it gets this "wrong" if statement. ;) > > #test > if __name__ == "__main__": > (g = dirGrep("c:\\winnt")) > files = g.findFiles(".py") > print g.findLines("java", files) > > When I try to run the program - python grep.py - I get the following error: > > C:\> python grep.py > File "grep.py", line 28 > if __name__ == '__main__': > ^ > SyntaxError: invalid syntax > > What am I doing wrong? > Thanks for any help > > From deets at nospam.web.de Wed Nov 22 11:43:19 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 22 Nov 2006 17:43:19 +0100 Subject: PyQt app in seperate thread References: <1164199026.728638.180000@j44g2000cwa.googlegroups.com> <1164204404.675906.59020@b28g2000cwb.googlegroups.com> <1164206635.601219.36860@j44g2000cwa.googlegroups.com> Message-ID: <4sjd17FvqtpmU1@mid.uni-berlin.de> > OK I see that now. Thanks for pointing that out. So basically, I can't > do what I want at all. That's a bit of a pain. Is there no way of > tricking Qt into thinking I'm running it in the main thread? Maybe you can either invert the thread-roles - that is, run your "main" application in a thread, and if needed start the Qt-thing, or you might consider spawning a process and using pyro. Which will work very neat, done so myself. Diez From noone at nowhere.com Wed Nov 15 09:23:14 2006 From: noone at nowhere.com (Josh) Date: Wed, 15 Nov 2006 09:23:14 -0500 Subject: sqlite3 views, if not exists clause References: Message-ID: <455b22d2$0$561$b45e6eb0@senator-bedfellow.mit.edu> "Tim Golden" wrote in message news:mailman.140.1163512445.32031.python-list at python.org... | Not a bug with the "sqlite3 api that comes with python 2.5." as such, | since .execute pretty much passes its parameters through to the database | engine. Rather, the syntax you're using is a relatively late addition | to the sqlite libs -- at least it fails on my 3.2.1 version of the | sqlite3 commmand-line tool, but succeeds on the latest download (3.3.8). | | I presume therefore that you build of Python is linked against an | older version of the sqlite libraries / DLL. Exactly right. Since the sqlite3 interface hasn't changed, the fix was simply to copy the newest sqlite3.dll into the python dll directory. Now I no longer have to catch and ignore the "already exists" exception thrown by python. Thanks! From grflanagan at yahoo.co.uk Sat Nov 4 06:09:45 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 4 Nov 2006 03:09:45 -0800 Subject: Programming Language that is Spreadsheet/Table Based In-Reply-To: References: <1162588208.533235.266100@k70g2000cwa.googlegroups.com> <1162626260.236167.157920@m73g2000cwd.googlegroups.com> Message-ID: <1162638585.016404.20270@m7g2000cwm.googlegroups.com> James Stroud wrote: > Gerard Flanagan wrote: > >> py> # the following is probably the trickiest, should it return a Table > >> py> # should it be illegal? > >> py> # should t['Last'] be the way to take the "slice" and get the col? > >> py> t[None, 'Last'] # 1d slice returns list (2nd dim. explicit) > >> ['Barker', 'Burnet', 'Danson', 'Cooper'] > > > > I can imagine manipulating columns at the Table creation stage - > > insert, append, delete column - but after that I think you would be > > dealing with rows more often. Personally, if I needed columns I would > > be happier with a list comprehension: > > [ (row['Last'], row['Age']) for row in t ] > > etc. > > To make a table from list comprehension in this way seems like it would > require some redundancy because a list comprehension only gets you a > list (of rows or lists). It seems if you wanted to work with your 2d > selection of data, then you would want to get a table back: > > data = [ (row['Last'], row['Age']) for row in t ] > t2 = Table(('Last','Age'), data) > > This seems, to me, to separates selection in the 2 dimensions and makes > it "backwards": > > data = [ (row['Last'], row['Age']) for row in t[1:3]] > t2 = Table(('Last','Age'), data) > > So a function would be needed to group the selection in a way that > reflects the organization of the table: > > t2 = t.subtable((1,3), ('Last','Age')) > > But then, since the latter seems a natural consequence of using list > comprehension for selection, how might one distinguish a range of > columns if not by a verbose function name? > > t2 = t.subtable_with_column_range((1,3), ('Last','Age')) > > The concept of slicing seems to take care of this. Maybe > > t2 = t.subtable(slice(1,3), slice('Last','Age')) > > But this begins to seem awkward and verbose to boot. Any suggestions on > adapting your idea of list comprehension to generate subtables? > What about symmetric 'load' and 'iterrows' methods for the Table class: t2 = Table() t2.load( t1.iterrows("LastName", "Age") ) def load(self, iterable): '''expecting tuples''' for lname, age in iterable: self.append( lname, age ) def iterrows(self, *args): '''returns a generator which itself returns tuples filtered by the column names in *args (via operator.itemgetter maybe?)''' There might be some value in comparing Microsoft's DataSet API. IIRC, you typically have: *UI* - DataView - DataSet - DataAdapter - *DATABASE* A DataSet is a collection of DataTables and has a lot of DB/XML functionality and so on. A DataView on the other hand is more lightweight and has mainly filtering and sorting functions and is designed to be bound to a GUI widget such as a DataGrid. You might have something along the lines of: ds = DataSet() # fill ds from datasource dt_customers = ds.tables["customers"] view = DataView( dt_customers ) view.rowfilter = "lastname LIKE 'A*' and Age < 60" I'm not saying imitate this, but maybe some value in studying the OO-bondage approach. All the best Gerard From fredrik at pythonware.com Tue Nov 14 06:23:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Nov 2006 12:23:33 +0100 Subject: __init__.py In-Reply-To: References: Message-ID: km wrote: > what is the use of __init__.py file in a module dir ? it tells Python that the directory is a package directory. if you have mydir/foo/__init__.py mydir/foo/module.py and mydir is on the path, you can do "import foo.module" or "from foo import module". if you remove the __init__.py file, Python will no longer look for submodules inside that directory. > Is it used to initialize variables that could be shared across sub > modules if set in __init__.py at root dir of module ? it's usually empty, or used to export selected portions of the package under more convenient names. given the example above, the contents of the __init__ module can be accessed via: import foo From fredrik at pythonware.com Sat Nov 18 05:09:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 18 Nov 2006 11:09:07 +0100 Subject: lxml/ElementTree and .tail In-Reply-To: <1163835505.102190.140060@b28g2000cwb.googlegroups.com> References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> <761846B7-E374-41FE-8804-CBB3D42FD4D2@snowtide.com> <1163835505.102190.140060@b28g2000cwb.googlegroups.com> Message-ID: Uche Ogbuji wrote: > I certainly have never liked the aspects of the ElementTree API under > present discussion. But that's not as important as the fact that I > think the above statement is misleading. There has always been a > battle in XML between the people who think the serialization is > preeminent, and those who believe some data model is preeminent, but > the reality is that XML 1.0 (an 1.1) is a spec *defined* by its > serialization. sure, the computing world is and has always been full of people who want the simplest thing to look a lot harder than it actually is. after all, *they* spent lots of time reading all the specifications, they've bought all the books, and went to all the seminars, so it's simply not fair when others are cheating. in reality, *all* interchange formats are easier to understand and use if you focus on a (complete or intentionally simplified) data model of the things being interchanged, and treat various artifacts of the byte-stream used by the wire format as artifacts, historical accidents based on what specification happened to be written before the other, or what some guy did or did not do in the seventies, as accidents, and esoteric arcana disseminated on limited-distribution mailing lists as about as relevant for your customer as last week's episode of American Idol. (XML is a bit unusual in this respect, but that's probably just some variation of the bikeshed effect. it's just text, and everyone with a keyboard knows what that is, so we don't need to use established software engineering practices, or think about security *at all* (Billion laughs? XXE?) or, for that matter, learn from people who's been doing data interchange in other domains since the dawn of time. and when they do appear anyway, and mess with our technology in ways that we haven't authorized, without reading our books or going to our seminars or subscribing to our mailing lists, we can write them off as "clueless muppet teenage genius code-jockeys", and keep patting our- selves on the back, while the rest of the world is busy routing around us, switching to well-understood XML subsets or other serialization formats, simpler and more flexible data models, simpler API:s, and more robust code. and Python ;-) From bignose+hates-spam at benfinney.id.au Mon Nov 13 00:56:14 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 13 Nov 2006 16:56:14 +1100 Subject: how do i map this? References: <1163387481.135930.167580@m7g2000cwm.googlegroups.com> <1163393708.532194.250580@k70g2000cwa.googlegroups.com> Message-ID: <87veljhou9.fsf@benfinney.id.au> "John Machin" writes: > Ben Finney wrote: > > You're printing a string, and never using that 'row' parameter. > > If that is so, why is he getting that message "TypeError: format > requires a mapping"? No idea. Probably because what the poster showed us is not code that shows the problem described. Original poster (and everyone who wants help with their program behaving unexpectedly): please ensure that you post a complete, minimal example of code that exhibits the unexpected behaviour. -- \ "Room service? Send up a larger room." -- Groucho Marx | `\ | _o__) | Ben Finney From fuzzyman at gmail.com Fri Nov 3 16:19:34 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 3 Nov 2006 13:19:34 -0800 Subject: Programming Language that is Spreadsheet/Table Based In-Reply-To: <1162588208.533235.266100@k70g2000cwa.googlegroups.com> References: <1162588208.533235.266100@k70g2000cwa.googlegroups.com> Message-ID: <1162588774.874189.240330@m73g2000cwd.googlegroups.com> Omar wrote: > I'm looking for a programming language or module that sorta looks and > feels like MS Excel (I love and think in tables), yet has the power and > open-endedness of python or javascript. I'm still pretty new to > python. > > any ideas? i've been having some fun with VBA in excel, but I want > something I can save as en exe and call my own creation, y'know? I think you'll have to build it. For .NET there are lots of third party grids available and a native one as well. You may want to look at the grid supplied with wxPython. Spreadsheets are effectively interfaces to functional programming, so this request isn't as odd as it may seem to some. You probably want to have a look at the PyCells project which can handle the dependency tracking you will need: which is harder than you might think. Fuzzyman http://www.voidspace.org.uk/python/index.shtml From fredrik at pythonware.com Sat Nov 4 11:49:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 04 Nov 2006 17:49:52 +0100 Subject: python GUIs comparison (want) In-Reply-To: <1162657420.655675.185930@e3g2000cwe.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <1162657420.655675.185930@e3g2000cwe.googlegroups.com> Message-ID: Mudcat wrote: > I have been using Tkinter for several years now. Recently I have been > thinking about switching to something else that may have a sharper > appearance. However I'm not sure what that may be, and if that > something else is *that* much better than what I'm already using. Tk 8.5 isn't that far away, though. http://www.markroseman.com/tcl/guide85.html From rridge at csclub.uwaterloo.ca Tue Nov 7 10:38:02 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 7 Nov 2006 07:38:02 -0800 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <7xk62ct5pf.fsf@ruckus.brouhaha.com> Message-ID: <1162913881.953664.254960@m73g2000cwd.googlegroups.com> Joe Seigh wrote: > Basically there's a race condition where an object containing the > refcount can be deleted between the time you load a pointer to > the object and the time you increment what used to be a refcount > and is possibly something else but definitely undefined. That doesn't really make sense. The object can't be deleted because the thread should already have a reference (directly or indirectly) to the object, otherwise any access to it can cause the race condition you describe. Ross Ridge From miles.chris at gmail.com Tue Nov 14 10:39:39 2006 From: miles.chris at gmail.com (Chris Miles) Date: Tue, 14 Nov 2006 15:39:39 +0000 Subject: Python speed on Solaris 10 Message-ID: I have found that the sunfreeware.com build of Python 2.4.3 for Solaris 10 is faster than one I can build myself, on the same system. sunfreeware.com doesn't bother showing the options they used to configure and build the software, so does anyone know what the optimal build options are for Solaris 10 (x86)? Here are some pybench/pystone results, and I include the same comparison of Python2.4.3 running on CentOS 4.3 on the same hardware (which is what prompted me to find a faster Python build in the first place). Python 2.4.3: System pybench Pystone (pystones/s) -------------------------------------------------------- Sol10 my build 3836.00 ms 37313.4 Sol10 sunfreeware 3235.00 ms 43859.6 CentOS 3569.00 ms 44247.8 My build: Python 2.4.3 (#1, Oct 15 2006, 16:00:33) [GCC 3.4.3 (csl-sol210-3_4-branch+sol_rpath)] on sunos5 sunfreeware.com build: Python 2.4.3 (#1, Jul 31 2006, 05:14:51) [GCC 3.4.6] on sunos5 My build on CentOS 4.3: Python 2.4.3 (#1, Jul 19 2006, 17:52:43) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 is the difference purely gcc minor version? -- http://chrismiles.info/ From jm.suresh at gmail.com Sun Nov 5 07:54:42 2006 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 5 Nov 2006 04:54:42 -0800 Subject: finding the list of the matched strings Message-ID: <1162731282.327715.49800@f16g2000cwb.googlegroups.com> Hi, I have a list of strings. And I want to find the subset which matches a particular regular expression. import re ll = ('a', 'b', 's1', 's2', '3s') p = re.compile('^s.*') newList = filter(lambda s: p.match(s), ll) I suppose there should be simple function to do this in re module. Is there any? I searched google, but could not find one, may be for keywords were not perfect. Thanks. Suresh From gagsl-py at yahoo.com.ar Thu Nov 9 19:20:12 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 09 Nov 2006 21:20:12 -0300 Subject: Tkinter check box behaviour - Windows / Linux discrepancy In-Reply-To: <1163114920.900203.306550@h48g2000cwc.googlegroups.com> References: <1163114920.900203.306550@h48g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20061109210226.05766278@yahoo.com.ar> At Thursday 9/11/2006 20:28, peter wrote: >I've come across a weird difference between the behaviour of the >Tkinter checkbox in Windows and Linux. The issue became apparent in >some code I wrote to display an image in a fixed size canvas widget. If >a checkbox was set then the image should be shrunk as necessary to fit >the canvas while if cleared it should appear full size with scrollbars >if necessary. > >The code worked fine under Linux (where it was developed). But under >Windows, the first click in the checkbox did nothing, then subsequent >clicks adjusted the size according to the PREVIOUS, not the current, >checkbox state. > >I've isolated the problem in the code below, which shows a single >checkbox and a label to describe its state. It works ok under Linux, >but in Windows it is always one click behind. > self.chkTest=tk.Checkbutton(frmMain,text='Click >me!',variable=self.intTest) > > self.chkTest.bind('',self.chkTest_click) Your code works fine in Linux just by accident. The action of button widgets must be associated to "command"; as you see, when the mouse button is released, the associated variable might not have been updated. Remove that bind call, and use: self.chkTest=tk.Checkbutton(frmMain,text='Click me!',variable=self.intTest, command=chkTest_click) (Should work fine on every platform - I've just tested on Windows) The command is fired after the mouse up event, and *only* if the previous mouse down was over the same widget. Your code doesn't work either if the user presses SPACE to toggle the button state; using "command" works fine in this case too. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From Laundro at gmail.com Fri Nov 24 02:55:48 2006 From: Laundro at gmail.com (LaundroMat) Date: 23 Nov 2006 23:55:48 -0800 Subject: reading id3 tags with python In-Reply-To: References: <1164328566.089711.89870@l12g2000cwl.googlegroups.com> Message-ID: <1164354948.000349.52170@m7g2000cwm.googlegroups.com> Heh, a description of the error would be nice indeed. Just a preliminary warning: with this code you will also be parsing directories. id3reader can't handle those ofcourse. Better add a check such as eg: if os.path.isfile(os.path.join(directory, file)): # do your thing laundro From cliff at develix.com Tue Nov 7 19:41:20 2006 From: cliff at develix.com (Cliff Wells) Date: Tue, 07 Nov 2006 16:41:20 -0800 Subject: Unicode/ascii encoding nightmare In-Reply-To: <1162856841.319591.73530@f16g2000cwb.googlegroups.com> References: <1162842650.780517.180360@b28g2000cwb.googlegroups.com> <1162846564.782883.259110@h54g2000cwb.googlegroups.com> <454fa3c9$0$13767$4fafbaef@reader3.news.tin.it> <1162854476.903789.5550@b28g2000cwb.googlegroups.com> <1162856841.319591.73530@f16g2000cwb.googlegroups.com> Message-ID: <1162946480.3592.6.camel@localhost.localdomain> On Mon, 2006-11-06 at 15:47 -0800, John Machin wrote: > Gabriel Genellina wrote: > > At Monday 6/11/2006 20:34, Robert Kern wrote: > > > > >John Machin wrote: > > > > Indeed yourself. Have you ever considered reading posts in > > > > chronological order, or reading all posts in a thread? > > > > > >That presumes that messages arrive in chronological order and > > >transmissions are > > >instantaneous. Neither are true. > > > > Sometimes I even got the replies *before* the original post comes. > > What is in question is the likelihood that message B can appear before > message A, when both emanate from the same source, and B was sent about > 7 minutes after A. Usenet, email, usenet/email gateways, internet in general... all in all, pretty likely. I've often seen replies to my posts long before my own post shows up. In fact, I've seen posts not show up for several hours. Regards, Cliff From cousinstanley at hotmail.com Fri Nov 24 19:47:53 2006 From: cousinstanley at hotmail.com (Cousin Stanley) Date: Fri, 24 Nov 2006 18:47:53 -0600 Subject: SQLite3__Python2.3-SQLite__Problem References: <1164325325_8617@sp6iad.superfeed.net> <1164401238.582515.226860@45g2000cws.googlegroups.com> Message-ID: <1164415673_14127@sp6iad.superfeed.net> >> .... >> I thought I remembered that the data bases created either way >> were always 100% transparent with each other and that I could >> use an SQLite3 data base either from the command line or from >> within Python without any problems at all .... > > My guess is that 2 years ago you were using sqlite 2, not 3. I think that is probably a very good guess .... >> I did a fair amount of Google-izing looking for related problems >> but didn't have much success .... > In that case your googler is absolutely rooted and should be > replaced immediately. > With mine, google("file is encrypted or is not a database") > produces as first hit (would you believe!?) My Googl-er is probably OK, but the Google-ee ( e.g. me ) is always in need of a tune-up .... :-) > Q: SQLite::Exceptions::\DatabaseException file is encrypted > or is not a database. > > A: It seems that sqlite databases created with version 2 > do not work with sqlite version 3 and vice versa I did re-build the data bases from the command line using sqlite3 instead of using the older ones from a couple of years back which I wasn't sure were sqlite2 or sqlite3 .... It seems that the older Debian Sarge version of the python2.3-sqlite package is the one that isn't directly compatible with sqlite3 dbs created at the command line .... I downloaded the PySQLite2 source package and compiled and installed it using distutils .... Now everything is also working fine under Debian Sarge and the dbs are OK either from the command line or from within Python .... Thanks a lot for taking the time to help .... -- Stanley C. Kitching Human Being Phoenix, Arizona ----== 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 nnorwitz at gmail.com Sat Nov 18 05:20:46 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 18 Nov 2006 02:20:46 -0800 Subject: How can I speed this function up? In-Reply-To: References: Message-ID: <1163845246.702167.16380@h48g2000cwc.googlegroups.com> Chris wrote: > This is just some dummy code to mimic what's being done in the real > code. The actual code is python which is used as a scripting language in > a third party app. The data structure returned by the app is more or > less like the "data" list in the code below. The test for "ELEMENT" is > necessary ... it just evaluates to true every time in this test code. In > the real app perhaps 90% of tests will also be true. As others have said, without info about what's happening in C, there's no way to know what's equivalent or fast enough. > So my question is how can I speed up what's happening inside the > function write_data()? Only allowed to use vanilla python (no psycho or > other libraries outside of a vanilla python install). Generally, don't create objects, don't perform repeated operations. In this case, batch up I/O. > def write_data1(out, data): > for i in data: > if i[0] is 'ELEMENT': > out.write("%s %06d " % (i[0], i[1])) > for j in i[2]: > out.write("%d " % (j)) > out.write("\n") def write_data1(out, data, map=map, str=str): SPACE_JOIN = ' '.join lines = [("ELEMENT %06d " % i1) + SPACE_JOIN(map(str, i2)) for i0, i1, i2 in data if i0 == 'ELEMENT'] out.write('\n'.join(lines)) While perhaps a bit obfuscated, it's a bit faster than the original. Part of what makes this hard to read is the crappy variable names. I didn't know what to call them. This version assumes that data will always be a sequence of 3-element items. The original version took about 11.5 seconds, the version above takes just over 5 seconds. YMMV, n From dlenski at gmail.com Thu Nov 9 14:06:06 2006 From: dlenski at gmail.com (Dan Lenski) Date: 9 Nov 2006 11:06:06 -0800 Subject: How to choose the right GUI toolkit ? In-Reply-To: <45536639$0$23587$426a34cc@news.free.fr> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163092380.301382.113470@m7g2000cwm.googlegroups.com> <45536639$0$23587$426a34cc@news.free.fr> Message-ID: <1163099166.793869.271900@h48g2000cwc.googlegroups.com> Christophe wrote: > Dan Lenski a ?crit : > > Nick and John S., thank you for the tip on wxPython! I'll look into it > > for my next project. I too would avoid Qt, not because of the GPL but > > simply because I don't use KDE under Linux and because Qt is not well > > supported under Cygwin or on native Windows. > Qt is very well supported under Windows! Avoid spreading lies please ;) > My apologies! I'm glad to be corrected on this. There are Cygwin packages for Qt as well, but I have heard about enough bugs to think I should avoid Qt. I have used enough Gtk apps that run flawlessly under Windows to have my hopes that it works well. > > ( and I must admit one of the reasons I avoid wx if possible, is because > I don't use Gnome under Linux and the look and feel of wx applications > is really horrible under KDE ) My understanding is that wx wraps Windows, OSX, Qt, and GTK+... I guess some of the wrappers fit the native apps better than others? Dan From __peter__ at web.de Thu Nov 30 05:56:14 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 30 Nov 2006 11:56:14 +0100 Subject: Slicing versus loops, was Re: for i in range() anti-pattern References: <1164812827.653386.323320@80g2000cwy.googlegroups.com> Message-ID: Duncan Booth wrote: > items[::2], items[1::2] = items[1::2], items[::2] Cool. I really should have found that myself. Peter From no-spam at no-spam-no-spam.invalid Sun Nov 12 09:52:45 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sun, 12 Nov 2006 15:52:45 +0100 Subject: numpy/scipy: correlation In-Reply-To: References: Message-ID: Robert Kern wrote: > robert wrote: >> Is there a ready made function in numpy/scipy to compute the correlation y=mx+o of an X and Y fast: >> m, m-err, o, o-err, r-coef,r-coef-err ? > > And of course, those three parameters are not particularly meaningful together. > If your model is truly "y is a linear response given x with normal noise" then > "y=m*x+o" is correct, and all of the information that you can get from the data > will be found in the estimates of m and o and the covariance matrix of the > estimates. > > On the other hand, if your model is that "(x, y) is distributed as a bivariate > normal distribution" then "y=m*x+o" is not a particularly good representation of > the model. You should instead estimate the mean vector and covariance matrix of > (x, y). Your correlation coefficient will be the off-diagonal term after > dividing out the marginal standard deviations. > > The difference between the two models is that the first places no restrictions > on the distribution of x. The second does; both the x and y marginal > distributions need to be normal. Under the first model, the correlation > coefficient has no meaning. Think the difference is little in practice - when you head for usable diagonals. Looking at the bivar. coef first before going on to any models, seems to be a more stable approach for the first step in data mining. ( before you proceed to a model or to class-learning .. ) Basically the first need is to analyse lots of x,y data and check for linear dependencies. No real model so far. I'd need a quality measure (coef**2) and to know how much I can rely on it (coef-err). coef alone is not enough. You get a perfect 1.0 with 2 ( or 3 - see below ) points. With big coef's and lots of distributed data the coef is very good by itself - its error range err(N) only approx ~ 1/sqrt(N) One would expect the error range to drop simply with # of points. Yet it depends more complexly on the mean value of the coef and on the distribution at all. More interesting realworld cases: For example I see a lower correlation on lots of points - maybe coef=0.05 . Got it - or not? Thus lower coefs require naturally a coef-err to be useful in practice. Now think of adding 'boring data': >>> X=[1.,2,3,4] >>> Y=[1.,2,3,5] >>> sd.correlation((X,Y)) # my old func (1.3, -0.5, 0.982707629824) # m,o,coef >>> numpy.corrcoef((X,Y)) array([[ 1. , 0.98270763], [ 0.98270763, 1. ]]) >>> XX=[1.,1,1,1,1,2,3,4] >>> YY=[1.,1,1,1,1,2,3,5] >>> sd.correlation((XX,YY)) (1.23684210526, -0.289473684211, 0.988433774639) >>> I'd expect: the little increase of r is ok. But this 'boring data' should not make the error to go down simply ~1/sqrt(N) ... I remember once I saw somewhere a formula for an error range of the corrcoef. but cannot find it anymore. http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#Trivia says: In MATLAB, corr(X) calculates Pearsons correlation coefficient along with p-value. Does anybody know how this prob.-value is computed/motivated? Such thing would be very helpful for numpy/scipy too. http://links.jstor.org/sici?sici=0162-1459(192906)24%3A166%3C170%3AFFPEOC%3E2.0.CO%3B2-Y tells: probable error of r = 0.6745*(1-r**2)/sqrt(N) A simple function of r and N - quite what I expected above roughly for the N-only dep.. But thus it is not sensitive to above considerations about 'boring' data. With above example it would spit a decrease of this probable coef-err from 0.0115628571429 to 0.00548453410954 ! And the absolute size of this error measure seems to be too low for just 4 points of data! The other formula which I remember seeing once was much more sophisticated and used things like sum_xxy etc... Robert PS: my old func is simply hands-on based on n,sum_x,sum_y,sum_xy,sum_xx,sum_yy=len(vx),vx.sum(),vy.sum(),(vx*vy).sum(),(vx*vx).sum(),(vy*vy).sum() Guess its already fast for large data? Note: numpy.corrcoef strikes on 2 points: >>> numpy.corrcoef(([1,2],[1,2])) array([[ -1.#IND, -1.#IND], [ -1.#IND, -1.#IND]]) >>> sd.correlation(([1,2],[1,2])) (1, 0, 1.0) >>> >>> numpy.corrcoef(([1,2,3],[1,2,3])) array([[ 1., 1.], [ 1., 1.]]) >>> sd.correlation(([1,2,3],[1,2,3])) (1, 0, 1.0) PPS: A compatible scipy binary (0.5.2?) for numpy 1.0 was announced some weeks back. Think currently many users suffer when trying to get started with incompatible most-recent libs of scipy and numpy. From gagsl-py at yahoo.com.ar Tue Nov 21 18:49:18 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 21 Nov 2006 20:49:18 -0300 Subject: Help! I need a list, not a pointer to it In-Reply-To: <20061121225304.67695.qmail@web56001.mail.re3.yahoo.com> References: <20061121225304.67695.qmail@web56001.mail.re3.yahoo.com> Message-ID: <7.0.1.0.0.20061121204215.040f31e0@yahoo.com.ar> At Tuesday 21/11/2006 19:53, Sorin Schwimmer wrote: >solutions=[] >matrix=[[1.0], [0], [0]] >j=0 >while j [...modify matrix...] > print matrix > solutions.append(matrix) # same result with matrix[:] >print solutions > >gives: >[[0], [1.0], [0]] >[[0], [0], [1.0]] >[[1.0], [0], [0]] >[[[1.0], [0], [0]], [[1.0], [0], [0]], [[1.0], [0], [0]]] >(i.e. the last value of matrix, three times) > >How can I end up with: >[[0], [1.0], [0]] >[[0], [0], [1.0]] >[[1.0], [0], [0]] >[[[0], [1.0], [0]], [[0], [0], [1.0]], [[1.0], [0], [0]]] >(i.e. each value of matrix)? Using matrix[:] gives you a _shallow_ copy of matrix - a new list, but its elements (lists themselves) are the original ones. You may want to use deepcopy() instead (or redesign your algorithm to not use those inner lists). -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From chris at kateandchris.net Wed Nov 22 13:39:02 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Wed, 22 Nov 2006 13:39:02 -0500 Subject: Programmatically replacing an API for another module In-Reply-To: <20061122183547.GA3929@kateandchris.net> References: <4562de7f$0$21252$426a34cc@news.free.fr> <20061122183547.GA3929@kateandchris.net> Message-ID: <20061122183902.GB3929@kateandchris.net> > > I'm just a bit loathe to download and install more stuff when > > something simpler appears to be near-at-hand. ...especially > > considering the page describing this module doesn't offer any download > > links! http://python-mock.sourceforge.net/ > How about mini-mock: > http://blog.ianbicking.org/minimock.html Oh yeah, and the download link for python-mock is: http://sourceforge.net/project/showfiles.php?group_id=138804 From lukasz.langa at gmail.com Sun Nov 26 17:21:26 2006 From: lukasz.langa at gmail.com (=?UTF-8?B?xYF1a2FzeiBMYW5nYQ==?=) Date: Sun, 26 Nov 2006 23:21:26 +0100 Subject: The Python Papers Edition One In-Reply-To: References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <7a9c25c20611222040q139ad3fera14a7afba6f60343@mail.gmail.com> <43c8685c0611222128r541a6fddtc4f2aa2d2e90f021@mail.gmail.com> Message-ID: <456A1366.5060608@gmail.com> Fredrik Lundh: > Tennessee Leeuwenburg wrote: > > >> If anyone has any good ideas for how to cope as a publisher with these >> difficulties, I'm all ears. >> > > has any of the format zealots posting to this thread actually > volunteered to produce any material for your publication? if not, I > suggest ignoring them. any bozo with a keyboard can contribute stop > energy to a project, but at the end, it's always the people *doing* > things that matters. > > +1 The Python Papers look very, very promising! I'm looking forward to reading next editions. Don't let whiners slow you down. PDF is a good choice, I personally like to print out longer things I read. IANAL, so I won't speak for or against CC licenses. They're used widely nowadays for a variety of applications (music, art, software, publications) so it seems they're doing their job. Keep up the good work! Best regards, ?ukasz Langa From http Tue Nov 7 03:19:49 2006 From: http (Paul Rubin) Date: 07 Nov 2006 00:19:49 -0800 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <454bd36c$0$2364$9b622d9e@news.freenet.de> <454ca6b4$0$151$9b622d9e@news.freenet.de> <7xpsc33zmh.fsf@ruckus.brouhaha.com> <454d587d$0$4361$9b622d9e@news.freenet.de> <7x7iyafg85.fsf@ruckus.brouhaha.com> <454DC638.2050802@v.loewis.de> Message-ID: <7x3b8voehm.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > Ah, but in the case where the lock# signal is used, it's known that > the data is not in the cache of the CPU performing the lock operation; > I believe it is also known that the data is not in the cache of any > other CPU. So the CPU performing the LOCK INC sequence just has > to perform two memory cycles. No cache coherency protocol runs > in that case. How can any CPU know in advance that the data is not in the cache of some other CPU? > But even when caching is involved, I don't see why there should be > more than three memory cycles. The MESI "protocol" really consists > only of two pins: HIT# and HITM#; the actual implementation is just > in keeping the state for each cache line, and in snooping. There > CPU's don't really "communicate". Instead, if one processor tries > to fill a cache line, the others snoop the read, and assert either > HIT# (when they have not modified their cache lines) or HITM# > (when they do have modified their cache lines). Assertions of > these signals is also immediate. OK, this is logical, but it already implies a cache miss, which costs many dozen (100?) cycles. But this case may be uncommon, since one hops that cache misses are relatively rare. > The worst case would be that one processor performs a LOCK INC, > and another processor has the modified value in its cache line. > So it needs to first flush the cache line, before the other > processor can modify the memory. If the memory is not cached > yet in another processor, the MESI protocol does not involve > additional penalties. I think for Python refcounts this case must occur quite frequently since there are many Python objects (small integers, None, etc.) whose refcounts get modified extremely often. IIRC, the SPJ paper that I linked claims that lock-free protocols outperform traditional lock-based ones even with just two processors. But maybe things are better with a dual core processor (shared cache) than with two separate packages. From sjmachin at lexicon.net Wed Nov 22 16:05:37 2006 From: sjmachin at lexicon.net (John Machin) Date: 22 Nov 2006 13:05:37 -0800 Subject: X class missing in Python :-) - Re: What's going on here? In-Reply-To: References: Message-ID: <1164229537.289097.172140@l39g2000cwd.googlegroups.com> robert wrote: > Dale Strickland-Clark wrote: > > 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. > >>>> a = object() > >>>> a > > > >>>> a.spam = 1 > > Traceback (most recent call last): > > File "", line 1, in ? > > AttributeError: 'object' object has no attribute 'spam' > >>>> class b(object): > > ... pass > > ... > >>>> a = b() > >>>> a > > <__main__.b object at 0xb7b4dcac> > >>>> a.spam = 1 > >>>> > > > > What is subclassing adding to the class here? Why can't I assign to > > attributes of an instance of object? > > > Python sooooo dynamic, but it lacks a (builtin) X-class ready for ad-hoc usage just like dict() :-) > I have in almost every app/toolcore-module this one: > > ------ > > class X(object): > def __init__(self,_d={},**kwargs): > kwargs.update(_d) > self.__dict__=kwargs > class Y(X): > def __repr__(self): > return ''%self.__dict__ > > ------ > > x=X(spam=1) > > Maybe X should be renamed to __builtin__.Object ... > > Have you considered putting it in one file and *importing* it into "almost every app/toolcore-module"? Have you considered that others may like to have something a little more elaborate, like maybe using the pprint module, or that the amount of data that would spew out might in some cases be so great that they wouldn't want that every time from repr(), preferring a dump-style method that wrote to a logfile? IMHO that's one of the enormous number of good points about Python; you can easily lash up something like that to suit yourself and inject it into any class you like; there's no central authority tying your hands behind your back. HTH, John From william.peterson at mchsi.com Wed Nov 15 16:44:54 2006 From: william.peterson at mchsi.com (Bill) Date: 15 Nov 2006 13:44:54 -0800 Subject: Will GPL Java eat into Python marketshare? In-Reply-To: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> References: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> Message-ID: <1163627094.880966.264060@h54g2000cwb.googlegroups.com> walterbyrd wrote: > Some think it will. > > Up untill now, Java has never been standard across different versions > of Linux and Unix. Some think that is one reason that some developers > have avoided Java in favor of Python. Now that Java has been GPL'd that > might change. > > IMO: it won't make much difference. But I don't really know. The change might also provide an opportunity for further expansion of jython, eating into Java "marketshare" From cgai at ksp-edv.de Mon Nov 6 04:44:08 2006 From: cgai at ksp-edv.de (Violet Blanchard) Date: Mon, 6 Nov 2006 10:44:08 +0100 Subject: waterbed presumptuous Message-ID: An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: calculation.gif Type: image/gif Size: 8990 bytes Desc: not available URL: From Iacopo.Marmo at gmail.com Thu Nov 9 16:12:12 2006 From: Iacopo.Marmo at gmail.com (Iacopo.Marmo at gmail.com) Date: 9 Nov 2006 13:12:12 -0800 Subject: how to create a multicolor "font-string" in pygame?? Message-ID: <1163106732.026203.111360@m73g2000cwd.googlegroups.com> Hi! I need to manipulate multicolor strings, i.e. strings with a color associated with each letter. Any suggestions? From vedran at v-programs.com Sat Nov 11 13:43:11 2006 From: vedran at v-programs.com (Croteam) Date: 11 Nov 2006 10:43:11 -0800 Subject: py2exe console removing Message-ID: <1163270591.454295.315750@f16g2000cwb.googlegroups.com> Hello, Can somebody tell me how to I remove console at script installing? Thanks. From cameron.walsh at gmail.com Fri Nov 10 03:09:49 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Fri, 10 Nov 2006 16:09:49 +0800 Subject: Printing to file, how do I do it efficiently? In-Reply-To: References: Message-ID: Robert Kern wrote: > Cameron Walsh wrote: >> Hi all, >> >> I have a numpy.array of 89x512x512 uint8's, set up with code like this: > > numpy questions are best asked on the numpy list, not here. At first I thought it was a generic python question, since it had more to do with writing array data to file rather than the specific format of the array data. > >> data=numpy.array([],dtype="uint8") >> data.resize((89,512,512)) > > You might want to look at using numpy.empty() here, instead. > Thanks! [...] >> I'm guessing that the slow part is the fact that I am converting the >> data to character format and writing it one character at a time. What >> is a better way of doing this, or where should I look to find a better way? > > data.tostring() > And here I see I was wrong, it was a numpy question. I assumed the tostring() method would produce the same output as printing the array to the screen by just calling "data". But of course, that would be the job of the __repr__() method. It is now ridiculously fast (<1second). Thank you for your help. Cameron. From deets at nospam.web.de Thu Nov 2 12:02:59 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 02 Nov 2006 18:02:59 +0100 Subject: creating new objects with references to them In-Reply-To: <1162483976.152660.121200@f16g2000cwb.googlegroups.com> References: <1162480549.786082.290980@b28g2000cwb.googlegroups.com> <1162482760.424782.244760@h48g2000cwc.googlegroups.com> <1162483976.152660.121200@f16g2000cwb.googlegroups.com> Message-ID: <4qumm0Fo82jqU1@uni-berlin.de> > >> Anyway, a simple list of Researchers should suffice for any of these >> purposes, and assuming you want to commit them all in one hit, you have >> a list of objects ready to iterate over. > > Ok, so in making a list does this mean that I won't have a name for > each instance? I just have to iterate over the list when I need them? > I'm not sure how I would do this if the user chooses just to save a > single record and not all of them. It means exactly that, and where is the problem? If the user choses to save just one record, she has to somehow select the one in question, hasn't she? So, she selects it from the list. And then you _know_ the index or even the record itself. If it helps you, think of the index of the list as the name of the record... Diez From walterbyrd at iname.com Tue Nov 21 11:40:47 2006 From: walterbyrd at iname.com (walterbyrd) Date: 21 Nov 2006 08:40:47 -0800 Subject: Spyce system requirements? Message-ID: <1164127246.887153.98820@m7g2000cwm.googlegroups.com> Does anybody know? What versionof Apache is required? If used with mod_python, what version of mod_python? Why version of Python is required? Any help appreciated, thanx. From jameshcunningham at gmail.com Wed Nov 29 08:46:45 2006 From: jameshcunningham at gmail.com (James Cunningham) Date: Wed, 29 Nov 2006 08:46:45 -0500 Subject: ANN: CherryPy 3.0 RC1 References: <1164807466.342293.138760@h54g2000cwb.googlegroups.com> Message-ID: <2006112908464516807-jameshcunningham@gmailcom> On 2006-11-29 08:37:46 -0500, "Christian" said: >> "Christian Wyglendowski" writes: >> >>> I'm happy to announce the first release candidate for CherryPy 3.0. > > Ben Finney wrote: >> >> Congratulations, I'm glad to see an announcement for CherryPy. >> >> Please, in future, don't send HTML message bodies to public forums; >> plain text is far better for such a wide audience. > > My apologies. I wrongly assumed that anyone using an email client that > only supported plain text would simply use the plain text part of the > email. Thanks for bringing this to my attention. > > Christian > http://www.dowski.com Some people are reading this on comp.lang.python. Best, James From jeff at taupro.com Mon Nov 27 05:06:10 2006 From: jeff at taupro.com (Jeff Rush) Date: Mon, 27 Nov 2006 04:06:10 -0600 Subject: A Call for Community Input re PyCon Slogans/Swag Message-ID: <456AB892.4080304@taupro.com> The PyCon organizers have established a short online poll to collect input from the Python community regarding the shirts, tote bag and slogans to be used at PyCon 2007, being held in Addison (Dallas), Texas Feb 23-25 2007. When we put out a prior call for slogan suggestions, we received 104 submissions. We've since reviewed them, narrowed them down to a number reasonable for voting on, and now you can help us decide the winner! Actually we're looking for two winners, one slogan for the T-shirt and another for the tote bag. Please take the poll at the following page. We've tried to keep it short, to respect your time. http://us.pycon.org/swagpoll Thanks! Jeff Rush Co-Chair PyCon 2007 From fuzzyman at gmail.com Tue Nov 7 19:18:15 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Nov 2006 16:18:15 -0800 Subject: [ANN] Movable Python 2.0.0 Beta 2 Message-ID: <1162945095.589606.174290@f16g2000cwb.googlegroups.com> I'm pleased to announce the release of `Movable Python 2.0.0 Beta 2 `_. There are now updated versions for Python 2.2 - 2.5, the Mega-Pack [#]_, and the free trial version. The most important changes in this release are : * Fixes for Pythonwin. The 'run' button and 'grep' dialog now work. * You can now specify a directory for config files. * The environment programs are run in is no longer pre-populated with variables. The **Movable Python** variables are now in a module called ``movpy``. You can see the full `changelog `_ below. You can download the updated version from : `Movable Python Download Pages `_ You can get the free trial version, from `Movable Python Demo & Other Files `_ What is Movable Python ================== **Movable Python** is a distribution of Python, for Windows, that can run without being installed. It means you can carry a full development environment round on a USB stick. It is also useful for testing programs with a 'clean Python install', and testing programs with multiple versions of Python. The GUI program launcher makes it a useful programmers tool, including features like : * Log the output of all Python scripts run * Enable Psyco for all scripts * Quick Launch buttons for commonly used programs * Configure multiple interpreters for use from a single interface It comes with the Pythonwin IDE. Plus many other features and bundled libraries. What's New ? ========== The changes in version 2.0.0 Beta 2 include : (Many thanks to Schipo and Patrick Vrijlandt for bug reports, fixes and suggestions.) Updated to Python 2.4.4 and wxPython 2.7.1 Fixed the bug with pylab support. Fixed problem with global name scope in the interactive interpreter. Everything moved out of the default namespace and moved into a module called 'movpy'. This contains : * ``filename`` = the path to the script we are running (the executable in interactive mode) * ``filedir`` = the directory that script is in (None when in interactive mode) * ``movpydir`` = the directory of the movpy executable * ``curdir`` = the cwd from which we have been called * ``configdir`` = the directory where config files are accessed from * ``libdir`` = the 'lib' directory that modules/packages are contained in * ``commandline`` != '' if '-c' was used * ``go_interactive`` = True if '-i' was set. * ``interactive`` = True if we are in an interactive session * ``interactive_mode`` is a function to enter interactive mode ``interactive_mode(localvars=None, globalvars=None, IPOFF=False, argv=None)`` * ``movpyw`` = True if we are running under movpyw rather than movpy The docs menu option will now launch the local version if available. Logfile is now closed using 'atexit' (should be closed *after* other 'atexit' functions finish). Logfile is flushed after every write to keep it in sync. A new command line option to specify the config file directory. ``movpyw --config ~\movpyfiles\config`` (The '~' is expanded to mean the user directory.) Fix for grep in Pythonwin IDE. Fix so that 'run' works in Pythonwin. (Browse button is disabled.) .. [#] The `Mega-Pack `_ is all the interpreters bundled together. It comes pre-configured so that you can test programs with any version of Python (including IronPython) from a single interface. From steve at holdenweb.com Wed Nov 1 21:24:01 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Nov 2006 02:24:01 +0000 Subject: logo design In-Reply-To: <1162432978.995731.291980@f16g2000cwb.googlegroups.com> References: <1162103065.460796.303660@f16g2000cwb.googlegroups.com> <1162270625.966859.194730@m73g2000cwd.googlegroups.com> <1162377308.044332.212610@i42g2000cwa.googlegroups.com> <1162432978.995731.291980@f16g2000cwb.googlegroups.com> Message-ID: alex23 wrote: > Xah Lee wrote: > >>No personal offense intended, but human animal's history is what? 3000 >>years at least in recorded history? And, all you can think of is what, >>the view points of a fraction of your personal life span? > > > Thank god evolution spat you out to lead us all to the light, huh? > > No personal offense intended, but you're a boring, elitist prick. > > - alex23 > This conversation has clearly descended to the level where it needs to be taken to email. Nobody wants to read this. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mail at microcorp.co.za Fri Nov 17 01:12:21 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 17 Nov 2006 08:12:21 +0200 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <45538b0d$0$26485$c3e8da3@news.astraweb.com> <4558b437$0$32430$c3e8da3@news.astraweb.com> Message-ID: <035301c70a1f$3d4144a0$03000080@hendrik> "Fredrik Lundh" wrote: > have anyone counted the number of colons used in this way by the OP, > in his first few posts ? (if there isn't a name for the law that > states that the number for a "let's remove the colons" proposal is > always greater than zero, someone should come up with one...) You just have - how do you want it to be immortalised? The effbot's law of colonic inevitability? - Badger (for Steve) From e0427417 at student.tuwien.ac.at Sat Nov 25 17:17:09 2006 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Sat, 25 Nov 2006 23:17:09 +0100 Subject: my small hashlib - using pythons hash-functions In-Reply-To: References: <45689fae$0$11868$3b214f66@tunews.univie.ac.at> <7x7ixjp7c2.fsf@ruckus.brouhaha.com> <4568b17a$0$11868$3b214f66@tunews.univie.ac.at> Message-ID: <4568c06d$0$10578$3b214f66@tunews.univie.ac.at> Fredrik Lundh wrote: > Mathias Panzenboeck wrote: > >> But the question is: *IS* this derived work? I mean, it's not copied >> code. >> It's the same hashing-logic, which I learned by watching pythons code. > > given that it's only a few lines of code, and there's hardly any other > way to write those lines if you want to implement the same algorithm, > I'd say it falls under "fair use". crediting the Python developers in > the source code should be good enough. > > > ic. I'll write a mail to the python developers then. The code in python looks like this (see code underneath), just if someone what's to know. I only used the logic of the parts I understand. ;) Objects/stringobject.c: static long string_hash(PyStringObject *a) { register Py_ssize_t len; register unsigned char *p; register long x; if (a->ob_shash != -1) return a->ob_shash; len = a->ob_size; p = (unsigned char *) a->ob_sval; x = *p << 7; while (--len >= 0) x = (1000003*x) ^ *p++; x ^= a->ob_size; if (x == -1) x = -2; a->ob_shash = x; return x; } Objects/dictobject.c: static dictentry * lookdict_string(dictobject *mp, PyObject *key, register long hash) { register size_t i; register size_t perturb; register dictentry *freeslot; register size_t mask = (size_t)mp->ma_mask; dictentry *ep0 = mp->ma_table; register dictentry *ep; /* Make sure this function doesn't have to handle non-string keys, including subclasses of str; e.g., one reason to subclass strings is to override __eq__, and for speed we don't cater to that here. */ if (!PyString_CheckExact(key)) { #ifdef SHOW_CONVERSION_COUNTS ++converted; #endif mp->ma_lookup = lookdict; return lookdict(mp, key, hash); } i = hash & mask; ep = &ep0[i]; if (ep->me_key == NULL || ep->me_key == key) return ep; if (ep->me_key == dummy) freeslot = ep; else { if (ep->me_hash == hash && _PyString_Eq(ep->me_key, key)) return ep; freeslot = NULL; } /* In the loop, me_key == dummy is by far (factor of 100s) the least likely outcome, so test for that last. */ for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { i = (i << 2) + i + perturb + 1; ep = &ep0[i & mask]; if (ep->me_key == NULL) return freeslot == NULL ? ep : freeslot; if (ep->me_key == key || (ep->me_hash == hash && ep->me_key != dummy && _PyString_Eq(ep->me_key, key))) return ep; if (ep->me_key == dummy && freeslot == NULL) freeslot = ep; } } From mahs at telcopartners.com Fri Nov 17 18:50:31 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 17 Nov 2006 15:50:31 -0800 Subject: Slicing / subsetting list in arbitrary fashion In-Reply-To: <455DF764.50105@lind-beil.net> References: <455DF764.50105@lind-beil.net> Message-ID: Gregg Lind wrote: > I wish something like this was part of the standard python installation, > and didn't require one to use Numpy or Numarray. This sort of list > subsetting is useful in many, many contexts. > Many of numpy's multi-dimensional slicing and indexing operations are implemented (for list and array.array types) in pure python in my pyarray module: http://svn.brownspencer.com/pyarray/trunk/ Michael From noway at sorry.com Sun Nov 12 19:05:08 2006 From: noway at sorry.com (Giovanni Bajo) Date: Mon, 13 Nov 2006 01:05:08 +0100 Subject: Find interface associated with default route? References: Message-ID: Neal Becker wrote: > A quick strace reveals that 'route' just reads /proc/net/route, so: > > def get_default_if(): > f = open ('/proc/net/route', 'r') > for line in f: > words = string.split (line) > dest = words[1] > try: > if (int (dest) == 0): > interf = words[0] > break > except ValueError: > pass > return interf And if you acknowledge that /proc/net/route is a CSV file, you can be more terse and clear: >>> import csv >>> def get_default_if(): ... f = open('/proc/net/route') ... for i in csv.DictReader(f, delimiter="\t"): ... if long(i['Destination'], 16) == 0: ... return i['Iface'] ... return None ... >>> >>> get_default_if() 'ppp0' -- Giovanni Bajo From george.sakkis at gmail.com Sun Nov 5 17:25:59 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 5 Nov 2006 14:25:59 -0800 Subject: simple way to un-nest (flatten?) list References: <9Ws3h.47668$r61.11004@text.news.blueyonder.co.uk> Message-ID: <1162765559.400161.306330@m73g2000cwd.googlegroups.com> djc wrote: > There is I am sure an easy way to do this, but I seem to be brain dead > tonight. So: > > I have a table such that I can do > > [line for line in table if line[7]=='JDOC'] > and > [line for line in table if line[7]=='Aslib'] > and > [line for line in table if line[7]=='ASLIB'] > etc > > I also have a dictionary > r= {'a':('ASLIB','Aslib'),'j':('JDOC', 'jdoc')} > so I can extract values > r.values() > [('ASLIB', 'Aslib'), ('JDOC', 'jdoc')] > > I would like to do > > [line for line in table if line[7] in ('JDOC','jdoc','Aslib','ASLIB')] > > so how should I get from > {'a':('ASLIB','Aslib'),'j':('JDOC','jdoc')} > to > ('Aslib','ASLIB','JDOC','jdoc') Meet itertools: from itertools import chain names = set(chain(*r.itervalues())) print [line for line in table if line[7] in names] George From george.sakkis at gmail.com Tue Nov 21 19:42:05 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 21 Nov 2006 16:42:05 -0800 Subject: Trying to understand Python objects References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> Message-ID: <1164156125.862887.314480@f16g2000cwb.googlegroups.com> walterbyrd wrote: > Reading "Think Like a Computer Scientist" I am not sure I understand > the way it describes the way objects work with Python. > > 1) Can attributes can added just anywhere? I create an object called > point, then I can add attributes any time, and at any place in the > program? For user-defined (i.e. not builtin) classes, yes. There are ways to prevent this (or at least it make it harder), but they're usually not worth it unless you have pretty good reasons to do it. And just in case you're wondering, "that's how php/c++/java/whatever does it" doesn't count as a pretty good reason. > 2) Are classes typically created like this: > > class Point: > pass > > Then attributes are added at some other time? Yes, you can do it. No, it is not typical. The typical is to initialize all class attributes in the class body, and all instance attributes in __init__: class Point(object): # prefer new-style classes in new code num_instances = 0 # a class attribute def __init__(self, x, y): self.x, self.y = x,y # instance attributes There are cases where this is not possible or desirable; Python doesn't get in your way in these cases, but they are certainly not typical. > 3) What is with the __underscores__ ?? They're special attributes, usually methods that perform "operator overloading". If the term doesn't mean anything to you, think of it as a method that is called implicitly by a specific operator. E.g. instead of having a normal method add() and then call it as a.add(b), you can define the special method __add__ and have it called when you write a + b. There are several details I left out but that's the gist of it. > 4) Are parameters passed to an class definition? > > class Whatever(params): > pass No, these are not parameters, they are the base (aka "super") clasess of Whatever. > I sort-of understand the way objects work with PHP. With PHP, the > classes are defined in one place - sort of like a function. To me, that > makes more sense. It makes sense in Python too, see point (2). The difference is that for the few cases that it either doesn't make sense or it's less convenient or desirable, Python doesn't get in your way. HTH, George From gagsl-py at yahoo.com.ar Fri Nov 24 19:29:41 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 24 Nov 2006 21:29:41 -0300 Subject: Capture file descriptors while running an external program In-Reply-To: <1164199248.3lj9jkctog8w@w3.mail.sapo.pt> References: <1164199248.3lj9jkctog8w@w3.mail.sapo.pt> Message-ID: <7.0.1.0.0.20061124211949.03970ad0@yahoo.com.ar> At Wednesday 22/11/2006 09:40, jfigueiras at sapo.pt wrote: >I have a problem with the module subprocess! >The problem is that the external software that I am running under >subprocess.Popen opens stdin, stdout, stderr, and other file descriptors to >write and read in the hard drive. As many other programs... >I know how to capture stdin, stdout and stderr, what I cannot do is to capture >the other file-descriptors. Is there any way to wrap those non-standard file >descriptors and make them write and read from a specific object that I define? >I know that I can use tmp files to do that, but i would like something running >without tmp files. I'm not sure what you mean by "non-standard file descriptors". The other program is free to open, read, write, etc any file he wants - are you trying to trap any file operation it may want to do? You *could* do such things -google for "code injection" and "API hooking"- but I doubt it's what you really want. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From peter.mosley at talk21.com Fri Nov 10 03:56:52 2006 From: peter.mosley at talk21.com (peter) Date: 10 Nov 2006 00:56:52 -0800 Subject: Tkinter check box behaviour - Windows / Linux discrepancy References: <1163114920.900203.306550@h48g2000cwc.googlegroups.com> Message-ID: <1163149012.716314.64340@h48g2000cwc.googlegroups.com> Thank you for those suggestions I've tried it on Windows and it seems fine (with the minor change to command=self.chkTest_click). I'm currently at work, with no access to Linux, so can't test it there until this evening. Muchas gracias! From nancydonnelly2006 at yahoo.com Tue Nov 21 06:12:49 2006 From: nancydonnelly2006 at yahoo.com (Nancy Donnelly) Date: Tue, 21 Nov 2006 03:12:49 -0800 (PST) Subject: Error Compiling Python Program Message-ID: <20061121111249.39412.qmail@web90308.mail.mud.yahoo.com> 7575Hi; I'm trying to install python-ldap-2.2.1.tar.gz on Python 2.3.5/FreeBSD 6.1 but I get this error: python setup.py install running install running build running build_py error: package directory 'Lib' does not exist How can I troubleshoot this? TIA, Nancy -------------- next part -------------- An HTML attachment was scrubbed... URL: From XX.XmcX at XX.XmclaveauX.com Sat Nov 25 07:56:14 2006 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Sat, 25 Nov 2006 13:56:14 +0100 Subject: Try to stop thread Using flag References: <1164456728.261093.184820@h54g2000cwb.googlegroups.com> Message-ID: http://candygram.sourceforge.net/ -- @-salutations Michel Claveau From m.yanowitz at kearfott.com Tue Nov 21 11:33:45 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Tue, 21 Nov 2006 11:33:45 -0500 Subject: Software Compatible with other versions? In-Reply-To: <456328B2.3080303@tim.thechases.com> Message-ID: <006201c70d8a$d00c3f60$0d7d12ac@kearfott.com> -----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 Tim Chase Sent: Tuesday, November 21, 2006 11:26 AM To: Laurent Pointal Cc: python-list at python.org Subject: Re: Software Compatable with other versions? >>>> I have been told that the .pyc are not compatable. Is it >>>> possible, to convert a 2.4.x .pyc to a 2.5 .pyc? >> >> The magic code. >> >> Just rm -rf *.pyc from your own scripts directories, they will >> be rebuilt. > > Just take care in the event that you have files that were > distributed in bytecode format (.pyc) rather than source > form...if you don't have any such .pyc files, then Laurent's > solution is fast and easy. If you do, you may have to protect > them before trying such a stunt. > > -tkc Yeah, that is my concern. We are mostly doing Windows and Linux. Due to some "export restriction", we are not allowed to distribute the .py files, and so distribute .pyc file. We also distribute the installer for Python 2.4.3 but do not require them to use it if they already have Python installed. Thus if we build with version 2.4.3, and distribute the .pyc files for 2.4.3 there is no way to make these .pyc files work if they use the latest 2.5 or some version before 2.4.x. Thanks in advance: Michael Yanowitz From deets at nospam.web.de Fri Nov 10 12:47:45 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 10 Nov 2006 18:47:45 +0100 Subject: Need help with Subversion bindings In-Reply-To: <1163170768.284700.95640@e3g2000cwe.googlegroups.com> References: <1163170768.284700.95640@e3g2000cwe.googlegroups.com> Message-ID: <4rjs9vFrrl52U1@mid.uni-berlin.de> paul.keating at nibc.com schrieb: > I'm trying to write a basic Subversion client because I need to > integrate Subversion with a product that keeps source code in a > database (so it has no notion of "working copy"). > > I have tried to translate the simple C examples in Garrett Rooney's > book into Python, but the very clever SWIG stuff has made the Python > access so different from the corresponding C that I can't do it. > > Example: I can create an apr array but I have no idea how to insert > something into it. In C you use APR_ARRAY_PUSH. In Python that doesn't > exist. Another example: I can create an apr hash, but I can't work out > how to look inside it. In C it is a struct with members count and max > etc. In Python it is a class that doesn't remotely resemble the > struct. > > Has anyone got a bare-bones bit of working Python that shows how to do > (say) an add or a checkout? There is an example of status in the > Subversion book but it's a toy: it doesn't show how you create an > authentication callback so it will only work locally. The nice python-ide eric3, written in python itself, features a subversion interface. Maybe you can take a look at that? Diez From fredrik at pythonware.com Mon Nov 13 08:17:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Nov 2006 14:17:37 +0100 Subject: httplib.InvalidURL: nonnumeric port: For characters in theproxypassword in URL References: <1163408210.915911.327430@k70g2000cwa.googlegroups.com><1163419232.632721.192360@i42g2000cwa.googlegroups.com> <1163423258.919153.281260@b28g2000cwb.googlegroups.com> Message-ID: "Phoe6" wrote: > - use urllib.quote() to covert the proxy url to a quoted one. you should use quote to convert the *password* to quoted form, not use it on the entire URL. From steve at holdenweb.com Tue Nov 7 21:40:18 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 07 Nov 2006 21:40:18 -0500 Subject: object data member dumper? In-Reply-To: <45510cc9$0$12164$88260bb3@free.teranews.com> References: <4550cddd$0$12104$88260bb3@free.teranews.com> <4550f442$0$20337$426a34cc@news.free.fr> <45510cc9$0$12164$88260bb3@free.teranews.com> Message-ID: tom arnall wrote: > Steve Holden wrote: > > >>Bruno Desthuilliers wrote: >> >>>tom arnall a ?crit : >>> >>> >>>>does anyone know of a utility to do a recursive dump of object data >>>>members? >>>> >>> >>> >>>What are "object data members" ? (hint: in Python, everything is an >>>object - even functions and methods). >>> >>>What is your real use case ? >> >>Basically it sounds like the OP wants to see the attribute values for an >>object (and those objects' attribute values, ...). Presumably the >>recursive descent could be stopped at the built-in types. > > > Yes, exactly. But what is 'OP'? > "original poster" (you) > >>I'm not familiar with any such thing. > > > I'm amazed that there is no way to easily look at the fundamental data > structures of a python program. I'm new to python - is there something I > don't know about the territory in this regard? > Well, new enough to be unaware that Python normally doesn't need such drastic measures for debugging. When you are building complex data structures such a form of output could get big really quickly. I've never come across anything like it in any other language that I have used. The most that's usually required is a __repr__() method that dumps the values of necessary data attributes. > >>The code of the standard library's >>pprint module might be a good place to start > > > I played around with this but it seems more targetted to looking at python > objects as opposed to user-defined. > It is, but it could be used as a basis for something more to your liking. > >>(and the suggested >>functionality might make a nice addition if we could work out exactly >>what the requirement was). > > > I would be glad if people would comment on my example as a step in this > direction. > I'd suggest you instead consider a mixin object that will add recursive data dump functionality to any such classes you require. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Tim.Golden at viacom-outdoor.co.uk Tue Nov 14 08:52:18 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 14 Nov 2006 13:52:18 -0000 Subject: sqlite3 views, if not exists clause In-Reply-To: <4559c572$0$560$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: [Josh] | I'm running into a problem when trying to create a view in my sqlite | database in python. I think its a bug in the sqlite3 api that | comes with python 2.5. | THIS DOES NOT WORK, but it should! | conn = sqlite3.connect(':memory:') | conn.execute("create table foo (a int,b int)") | conn.execute('create view if not exists bar as select * from foo') | it fails with exception "sqlite3.OperationalError: near | "not": syntax error" Not a bug with the "sqlite3 api that comes with python 2.5." as such, since .execute pretty much passes its parameters through to the database engine. Rather, the syntax you're using is a relatively late addition to the sqlite libs -- at least it fails on my 3.2.1 version of the sqlite3 commmand-line tool, but succeeds on the latest download (3.3.8). I presume therefore that you build of Python is linked against an older version of the sqlite libraries / DLL. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From e0427417 at student.tuwien.ac.at Sun Nov 19 15:35:24 2006 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Sun, 19 Nov 2006 21:35:24 +0100 Subject: a few extensions for the itertools Message-ID: <4560bfb0$0$10578$3b214f66@tunews.univie.ac.at> I wrote a few functions which IMHO are missing in python(s itertools). You can download them here: http://sourceforge.net/project/showfiles.php?group_id=165721&package_id=212104 A short description to all the functions: icmp(iterable1, iterable2) -> integer Return negative if iterable1 < iterable2, zero if iterable1 == iterable1, positive if iterable1 > iterable1. isum(iterable, start=0) -> value Returns the sum of the elements of a iterable plus the value of parameter 'start'. When the iterable is empty, returns start. iproduct(iterable, start=0) -> value Returns the product of the elements of a iterable times the value of parameter 'start'. When the iterable is empty, returns start. forall(predicate, iterable, default=True) -> bool Returns True, when for all elements x in iterable predicate(x) is True. When the iterable is empty, returns default. forany(predicate, iterable, default=False) -> bool Returns True, when for any element x in iterable predicate(x) is True. When the iterable is empty, returns default. take(n,iterable) -> iterator returns a iterator over the first n elements of the iterator drop(n,iterable) -> iterable drops the first n elemetns of iterable and return a iterator over the rest heads(iterable) -> iterator over all heads example: for head in heads([1,2,3,4,5,6,7,8,9]): print head output: [] [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8, 9] tails(iterable) -> iterator over all tails example: for tail in tails([1,2,3,4,5,6,7,8,9]): print tail output: [1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6, 7, 8, 9] [3, 4, 5, 6, 7, 8, 9] [4, 5, 6, 7, 8, 9] [5, 6, 7, 8, 9] [6, 7, 8, 9] [7, 8, 9] [8, 9] [9] [] fcain(funct,*functs) -> function(...,***) fcain(f1,f2,...,fn)(*args,*kwargs) equals f1(f2(...fn(*args,*kwargs))) From Thomas.Ploch at gmx.net Thu Nov 30 13:28:43 2006 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Thu, 30 Nov 2006 19:28:43 +0100 Subject: Automatic increment In-Reply-To: <8094b1b60611301008n36969305p48bec2c8a0e10ec1@mail.gmail.com> References: <8094b1b60611301008n36969305p48bec2c8a0e10ec1@mail.gmail.com> Message-ID: <456F22DB.9080605@gmx.net> Gheorghe Postelnicu schrieb: > Hi, > > I have a situation of the following type: > > for line in lineList: > for item in line.split() > myArray[counter, itemCounter] > itemCounter = itemCounter + 1 > counter = counter +1 > > Is there a way to get rid of the manual incrementation of the 2 counters? > > Thanks, for counter in xrange(len(lineList)): for itemCounter in xrange(len(lineList[counter].split())) myArray[counter, itemCounter] Thomas From sjmachin at lexicon.net Thu Nov 16 03:14:08 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 16 Nov 2006 19:14:08 +1100 Subject: Yield In-Reply-To: References: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> <455b4f9f$1@usenet01.boi.hp.com> <1163659530.752607.120880@m73g2000cwd.googlegroups.com> <455c15ca$1@news.eftel.com> Message-ID: <455c1ddf@news.eftel.com> On 16/11/2006 7:00 PM, Fredrik Lundh wrote: > John Machin wrote: > >>> I would like to thanks Fredrik for his contribution to improve that. >> >> Call me crazy, but after an admittedly quick read, the version on the >> wiki seems to be about word for word with on the docs.python.org version. > > maybe he was thinking about the article I posted, or the FAQ link I > posted in a followup: > > http://effbot.org/pyfaq/what-is-a-generator.htm > > which was based on my article and the glossary entry from the tutorial: > > http://effbot.org/pytut/glossary.htm#generator Quite possibly. > >> Could you please tell us how you think the wiki version is an >> improvement? > > an "add comment" link? direct URL:s for all concepts in the language? > extensive hyperlinking? semantic retargetable markup? Yes, they're great. Maybe I was thinking about the text contents only :-) Cheers, John From http Fri Nov 3 02:25:15 2006 From: http (Paul Rubin) Date: 02 Nov 2006 23:25:15 -0800 Subject: Javascript is turning into Python?! Message-ID: <7xwt6dkn50.fsf@ruckus.brouhaha.com> [Correction of earlier accidental crosspost] I hadn't seen this before. New Javascript 1.7 features: - Generators - Iterators - Array comprehensions - Destructuring assignment Sounds like another language we know. http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7 From antonioskatsikadamos at yahoo.com Wed Nov 8 05:31:33 2006 From: antonioskatsikadamos at yahoo.com (Antonios Katsikadamos) Date: Wed, 8 Nov 2006 02:31:33 -0800 (PST) Subject: MODULE mx.DateTime Message-ID: <20061108103133.46775.qmail@web58104.mail.re3.yahoo.com> Hi all. I am using python2.4 on suse linux 10.1 and i want to import the mx.DateTime module. does anyone know where i can find this module and how i can install it on linux? I would appreciate any help. thnx a lot kind regards, Antonios --------------------------------- Access over 1 million songs - Yahoo! Music Unlimited. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tom at t0mb.net Sat Nov 18 17:32:08 2006 From: tom at t0mb.net (tom) Date: Sat, 18 Nov 2006 22:32:08 +0000 Subject: syntax error in sum(). Please explicate. In-Reply-To: References: Message-ID: <455F89E8.4080206@t0mb.net> Michael Press wrote: > I have not written python codes nor run any. I saw this > code posted and decided to try it. It fails. I read the > tutorial and the entry for the built in function sum, > but still do not see the problem. The code was cut and > paste. Please help. Thanks. > > _________________________BEGIN_CODE_________________________ > #!/usr/bin/python > > ps = [none, 2,3,5,7,11,13,17,19,23,29] > > None has a capital N ^ > def phi(x, a): > return x - sum(phi(x // ps[i+1], i) for i in range(a)) > > def pi(n): > from math import sqrt > if n <= 1: > return 0 > a = pi(int(sqrt(n))) > return phi(n, a) + a - 1 > __________________________END_CODE__________________________ > > Here is the result of running it: > > File "/Users/mdp/source/prime_counter_python", line 6 > return x - sum(phi(x // ps[i+1], i) for i in range(a)) > ^ > SyntaxError: invalid syntax > > can you paste the complete code? I'm not sure why that's a syntax error there. with a bit of fudging it seems to run in the interpreter ok... > Here are some lines from python -v: > > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information > > From me at tim-adler.com Tue Nov 28 03:01:37 2006 From: me at tim-adler.com (Tim Adler) Date: 28 Nov 2006 00:01:37 -0800 Subject: Error when installing the Python Imaging Library Message-ID: <1164700897.128779.180580@j44g2000cwa.googlegroups.com> Hey everybody, I'm quite new to Python. I'm working on a webproject with Django and need to install the Python Imaging Library. It worked fine under Mac OS but when I try it on my Linux server. It gives me this error: PasteBin Link: http://phpfi.com/179314 I don't really know what is wrong. Can somebody point me directions. I really need the PIL to work. Thx, Tim From bbull at optiosoftware.com Fri Nov 3 16:49:17 2006 From: bbull at optiosoftware.com (WakeBdr) Date: 3 Nov 2006 13:49:17 -0800 Subject: WSDL? In-Reply-To: <454ba334$0$12110$88260bb3@free.teranews.com> References: <454ba334$0$12110$88260bb3@free.teranews.com> Message-ID: <1162590557.043667.20130@m73g2000cwd.googlegroups.com> XMLRPC and SOAP are the two I'm working with right now. tobiah wrote: > Is WSDL the right answer for in house communication > between programs written in different languages, or > is it more for publishing interfaces for use by parties > outside your own company? > > What else is available for sharing complex structures > with processes running programs that were written in > other languages? > > Thanks, > > Toby > > -- > Posted via a free Usenet account from http://www.teranews.com From aj108778 at gmail.com Sun Nov 12 02:14:32 2006 From: aj108778 at gmail.com (Doug) Date: 11 Nov 2006 23:14:32 -0800 Subject: Fredrik Lundh [was "Re: explicit self revisited"] In-Reply-To: References: <1163288444.893136.42030@h54g2000cwb.googlegroups.com> Message-ID: <1163315672.921664.306460@e3g2000cwe.googlegroups.com> Fredrik Lundh wrote: > Doug wrote: >> >> Fredrik Lundh wrote: >>> Fredrik Lundh wrote: >>> > cannot all you clueless trolls who cannot think of a single useful thing >>> > to contribute to Python start your own newsgroup? >> >>> and before anyone complains; please note that they're working through >> >>> http://www.effbot.org/pyfaq/design-index.htm >> >> That site is a bunch of FUD - >> The explicit self is there simply because OOP was tacked onto python as >> an afterthought. >> Why not just be honest about it. It's too late to change Python's >> syntax. It just means a little extra typing. If it really bothers >> someone, use "s" instead of "self" or else use Ruby. > > the official FAQ is a bunch of FUD? are you sure you know what FUD means? > > You idiot. Putting the word "official" in front of something doesn't mean it can't be FUD. Especially when it is written by people such as yourself. Have you not paid attention to anything happening in politics around the world during your lifetime? And yes, actually, the dash after FUD was where I was going to link to a definition of FUD to show I really meant to use that term. It doesn't appear that you believe anything that isn't on your own effbot site, however. From deets at nospam.web.de Thu Nov 9 17:55:46 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 09 Nov 2006 23:55:46 +0100 Subject: Simple question to split In-Reply-To: <4rhov8Frk45nU1@mid.uni-berlin.de> References: <4rhov8Frk45nU1@mid.uni-berlin.de> Message-ID: <4rhpvgFrneqhU2@mid.uni-berlin.de> Matthias Winterland schrieb: > Hi, > > I have a simple question. When I read in a string like: > a='1,2,3,4,5 6 7,3,4', can I get the list l=[1,2,3,4,5,6,7,3,4] with a > single split-call? Nope. But you could replace the commas with spaces, and then split. Diez From rrr at ronadam.com Thu Nov 16 14:22:47 2006 From: rrr at ronadam.com (Ron Adam) Date: Thu, 16 Nov 2006 13:22:47 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <45538b0d$0$26485$c3e8da3@news.astraweb.com> <4558b437$0$32430$c3e8da3@news.astraweb.com> Message-ID: Steve Holden wrote: > I'm always surprised by the amount of energy that's put into this type > of discussion - even the OP has suggested that this isn't a big issue. > If it's not a big issue why is this thread still going? Every language > has a syntax. Why not just accept it as a given and get on with more > productive activities? It's because it's not an issue with an obviously (clear to everyone) good or bad answer. Obvious bad answer -> short discussion Obvious good answer -> short discussion which spawns many long discussion about the not so obviously details. * Nearly a toss up -> really long discussion that rehashes things over and over from various micro points of view. Even though it's pretty much known this won't change, people still want the clarity of an obvious answer even if an obvious solution doe not exist, so the thread continues. And of course what is obvious or not isn't obvious to everyone, so that too is a long discussion. ;-) But I think this thread has a second underlying attribute that appeals to the participants. It isn't so much an effort to change anything as it is an effort to explore and understand why things where made the way they are. To those who already know, this seems silly, but to those who are still learning, it seems important. This could be broken down a bit more, but then we would get into long debates on the best non-obvious ways to do that. ;-) Cheers, Ron From chris at kateandchris.net Mon Nov 20 15:54:45 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Mon, 20 Nov 2006 15:54:45 -0500 Subject: FAQ: How do I calculate what quoted strings and numbers mean? In-Reply-To: <1164050436.816237.63130@b28g2000cwb.googlegroups.com> References: <1163168083.054745.32170@f16g2000cwb.googlegroups.com> <1163579122.362383.203240@k70g2000cwa.googlegroups.com> <1164050436.816237.63130@b28g2000cwb.googlegroups.com> Message-ID: <20061120205445.GA29413@kateandchris.net> On Mon, Nov 20, 2006 at 11:20:37AM -0800, p.lavarre at ieee.org wrote: > > but the os module isn't very far away > > I see Python defines some evals that apparently don't import os, such > as: > > int('0x100'[2:], 0x10) > float('1.23e+4') > binascii.unhexlify('4142') > > Does Python also define an eval that doesn't import os for literal > string args? > > For example, suppose someone gives me source strings like > repr('\a\r\n') when I need byte strings like '\a\r\n'. > http://docs.python.org/ref/strings.html lists the escapes that need > eval'ling, especially the comparatively heavy and Python-specific \N{} > escape. You can use string encoding and decoding to do what you want: >>> a = r'hello\nthere' >>> print a hello\nthere >>> print a.decode('string_escape') hello there you can find other escape type encodings here: http://docs.python.org/lib/standard-encodings.html -Chris From wilson1442 at bellsouth.net Mon Nov 6 08:48:03 2006 From: wilson1442 at bellsouth.net (JW) Date: Mon, 06 Nov 2006 08:48:03 -0500 Subject: Building C extensions References: Message-ID: On Mon, 06 Nov 2006 14:03:54 +0100, Paolo Pantaleo wants to build a C extension (presumably for Windows): A few months ago, I suffered the same misfortune of needing to port a pyrex-generated extension to Windows. I'm sure it's easier than I made it, but have a look at the thread: http://tinyurl.com/yb4bps If you're developing under Windows (you poor fellow!), you may actually have a slightly easier time than did I. Jim Wilson Gainesville, FL From richard.charts at gmail.com Wed Nov 8 07:49:16 2006 From: richard.charts at gmail.com (Richard Charts) Date: 8 Nov 2006 04:49:16 -0800 Subject: Python deployment options. In-Reply-To: <1162986129.233443.268730@h54g2000cwb.googlegroups.com> References: <1162982262.010438.99260@f16g2000cwb.googlegroups.com> <1162985073.163257.110180@m73g2000cwd.googlegroups.com> <1162986129.233443.268730@h54g2000cwb.googlegroups.com> Message-ID: <1162990156.204577.198720@h48g2000cwc.googlegroups.com> king kikapu wrote: > I see...So, if these are the only options, the only "safe" bet is to > install the language on the machine (beeing Win, Linux or Mac) > and execute the .py files, right ?? > > Well on a Win machine, probably. Almost every Linux machine you come across will have (most likely a fairly recent build of) python. For Macs, I'm not so sure but it's probably closer to Linux than Win. From dale at riverhall.nospam.co.uk Wed Nov 1 16:00:37 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Wed, 01 Nov 2006 21:00:37 +0000 Subject: Hooking file open References: Message-ID: You might consider trapping calls to file() too, which is an alias for open(). Also, I think I'd do my logging before calling the real function. It depends how you want to deal with exceptions. Farshid Lashkari wrote: > Hi, > > My goal is to detect all (or most) file dependencies of a script (i.e. > modules, dlls, data files). Currently, after a script is finished > executing I use sys.modules to determine all module dependencies, and I > use win32process.EnumProcessModules to determine DLL dependencies. This > works reasonably well, however I would still like to detect dependencies > from regular file open calls. > > I did a little test by modifying __builtins__.open to point to a custom > function that forwards the call to the original open function and saves > the filename to a list. It seemed to work for simple test cases. Here is > the code: > > def open_hook(*args,**kwargs): > r = open_real(*args,**kwargs) > saveFileName(args[0]) > return r > > open_real = __builtins__.open > __builtins__.open = open_hook > > Is this a safe approach? Is there a more efficient way of doing this? I > realize that some dependencies will still fall through my checks, > especially file opens from C extensions, which is fine. I just want to > be able to detect the most common use cases. Any other suggestions are > appreciated. > > -Farshid -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From tenax.raccoon at gmail.com Mon Nov 13 13:30:47 2006 From: tenax.raccoon at gmail.com (Jason) Date: 13 Nov 2006 10:30:47 -0800 Subject: Singleton Class Exception References: <1163437486.036537.270190@h54g2000cwb.googlegroups.com> <1163440038.901759.112130@h54g2000cwb.googlegroups.com> Message-ID: <1163442647.764741.227280@k70g2000cwa.googlegroups.com> I threw together two different singleton classes. They both ensure that the initializers and destructors can be called at most once. (The ImmortalSingleton won't ever have its destructor called unless the programmer manually forces things.) I haven't extensively tested these things, so handle this code like a rabid wildebeest. Observe that Python may not call your destructors when you expect. IAnd again, you probably want the Borg pattern. Still, this was an interesting exercise to do. --- Code Starts --- class MortalSingleton(object): """This class implements a 'mortal' singleton pattern. Classes derived from this class cannot be directly instantiated or take arguments in their initializers. The GetSingleton() class method returns a reference to a single instance, or creates a single instance as needed. This class only keeps a weak reference to the single instance. This means that, if all hard references are destroyed, the instance can be destroyed by Python (and the __del__ method *could* be called, depending on implementation). Thus, the single-ton is mortal. This could be used as a mix-in class, assuming that the other classes do not over-ride the __new__() method (which prevents willy-nilly instantiation). Note that if you need all instances to share state, you probably want to use the Borg pattern. Comments on this travesty are appreciated. *grin* """ def __new__(cls, *args, **keyargs): # Raise a run-time error preventing direct instantiation raise RuntimeError( 'Do not instantiate %s directly. Use the %s.GetSingleton()' 'class method.' % (cls.__name__, cls.__name__) ) @classmethod def GetSingleton(cls): from weakref import ref retObject = getattr(cls, '_instance', lambda : None)() if retObject is None: # Create a new object with the given class retObject = object.__new__(cls) # The initializer must be manually called in this case retObject.__init__() cls._instance = ref(retObject) return retObject class ImmortalSingleton(object): """This class implements a classic 'immortal' singleton pattern. Classes derived from this class will allow only one instance to exist. Since the class caches a hard reference to the single pattern, it doesn't die unless the programmer gets rid of all references and manually deletes the cache reference. Note that you probably want to use a variant of the Borg class rather than this.""" def __new__(cls, *args, **keyargs): # Raise a run-time error preventing direct instantiation raise RuntimeError( 'Do not instantiate %s directly. Use the %s.GetSingleton()' 'class method.' % (cls.__name__, cls.__name__) ) @classmethod def GetSingleton(cls): retObject = getattr(cls, '_instance', lambda : None)() if retObject is None: # Create a new object with the given class retObject = object.__new__(cls) # The initializer must be manually called in this case retObject.__init__() cls._instance = retObject return retObject From dlenski at gmail.com Wed Nov 8 13:38:18 2006 From: dlenski at gmail.com (Dan Lenski) Date: 8 Nov 2006 10:38:18 -0800 Subject: How to choose the right GUI toolkit ? Message-ID: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> Hi all, I'm a recent, belated convert from Perl. I work in a physics lab and have been using Python to automate a lot of measurement equipment lately. It works fabulously for this purpose. Recently I've wanted to start writing GUIs for some of my programs, for data visualization and to make the programs easier to use for some of my co-workers. So far I've experimented with two Python GUI toolkits: Tkinter and PyGTK. I've had some issues with each: * PyGTK - not very "pythonic", in my opinion. Have to use get_ and set_ methods rather than properties. Have to write ugly things like textview.insert(textview.get_end_iter(), ...) to append text to a text buffer. No useful doc strings, which makes experimenting with new widgets in IPython a huge pain. The toolkit feels very "heavyweight". I don't want to write an XML file and an "action group" just to make a piddly little menubar with 10 items. I'm an avid Gnome fan, and love the professionalness and completeness of GTK, but PyGTK seems frustratingly C-like compared to the wonderfully designed high-level abstractions I've come to love in Python! * TkInter - Seems easy to learn, and better for quick "lightweight" GUIs. I wrote a complete working instrument GUI in less than a day of figuring things out. Not very Pythonic in terms of creating and modifying widgets. No factory functions to quickly create menu items. My biggest problem with Tkinter is that it is very unreliable under Cygwin: programs freeze and slow intermittently and the tkMessageDialog stock dialog boxes show no visible text. So, is there another toolkit I should be looking at? Having something that can run easily on Cygwin and native Windows is a priority so that I can quickly move programs to new measurement computers. I like GTK a lot and Tk is growing on me too.. are there any higher-level "wrapper" toolkits for GTK and Tk? Thanks for any advice! Dan Lenski University of Maryland From vatamane at gmail.com Tue Nov 7 17:40:18 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 7 Nov 2006 14:40:18 -0800 Subject: Finding Nonzero Elements in a Sparse Matrix References: <1162937813.360645.3040@h54g2000cwb.googlegroups.com> Message-ID: <1162939218.006857.100300@h54g2000cwb.googlegroups.com> The function you might want is nonzero() or flatnonzero() >>> from numpy import * >>> a=array([ [1,2],[0,4] ]) >>> a array([[1, 2], [0, 4]]) >>> flatnonzero(a) array([0, 1, 3]) nonzero() will return the a sequence of index arrays of non zero elements flatnonzero() returns the non-zero elements of the flattened version of the array. Cheers, Nick Vatamaniuc deLenn wrote: > Hi, > > Does scipy have an equivalent to Matlab's 'find' function, to list the > indices of all nonzero elements in a sparse matrix? > > Cheers. From seandavi at gmail.com Wed Nov 29 10:09:45 2006 From: seandavi at gmail.com (SeanDavis12) Date: 29 Nov 2006 07:09:45 -0800 Subject: Calling functions with dynamic arguments Message-ID: <1164812985.794957.26530@l12g2000cwl.googlegroups.com> I have a dictionary like: {"a":1, "b":2} and I want to call a function: def func1(a=3,b=4): print a,b so that I get a=1,b=2, how can I go about that? Thanks, Sean From grante at visi.com Wed Nov 1 11:12:40 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 01 Nov 2006 16:12:40 -0000 Subject: 3d programming without opengl References: <1162394216.958479.297410@e64g2000cwd.googlegroups.com> Message-ID: <12khhro1hph7q38@corp.supernews.com> On 2006-11-01, Will McGugan wrote: > If you are worried about running your 3d app on older > machines, OpenGL will typically fall back to software > rendering if the hardware isn't available. That's true. OpenGL (which will do SW rendering) will certainly be available on most/all Linux machines (except for headless or text-only servers). > Although you would have to be running it on an ancient PC if > that is an issue. Not true. None of my machines have hardware 3D acceleration. One is only 9 months old, the others are 2-3 years old. However, OpenGL's software rendering works fine and has sufficient performance for most things short of 3D video games. -- Grant Edwards grante Yow! Look into my eyes and at try to forget that you have visi.com a Macy's charge card! From onurb at xiludom.gro Mon Nov 6 05:19:47 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 06 Nov 2006 11:19:47 +0100 Subject: Creating db front end or middleware. In-Reply-To: <454a3347$0$12193$88260bb3@free.teranews.com> References: <454a3347$0$12193$88260bb3@free.teranews.com> Message-ID: <454f0c45$0$21382$426a74cc@news.free.fr> tobiah wrote: > Let's say I want to write a new tool to do > something to, or report on people in a database. > Each tool is going to have to have all sorts of > routines that know about the relationship between > the data. The first thought is to write a library > of routines that do things like, change_address(), > or fire_employee() or whatever. > Whoops, now we've decided to move to python. I > have to write all of that again. > > So I thought, shouldn't there be a cloud that sits > in front of the database to which I can ask these > services of? Some process that awaits requests for > information, or handles new incoming data. Now new > apps written in any language should be able to use a basic protocol in > order to get the work done. > > The question then, is what the best way to do this is. The first question then is: do you really need a middleware ? Most RDBMSs are already full-blown server applications - with support for authentification, permissions, triggers and stored procedures - that can be accessed by client programs in almost any language. Now if you effectively want/need a web service, it seems that the canonical solutions are XMLRPC and SOAP. But if you already use a RDBMS, this web service should IMHO mostly be designed as an higher-level interface to the RDBMS, not as a full-blown app managing domain/business rules (which is the job of the RDBMS). IOW, it should be still possible for applications to directly interact with the RDBMS. > First I thought of using cherrypy to sit and listen to > POST requests, but this would make passing complex structures > extremely inconvenient. There are XMLRPC packages for most languages, that knows how to do the native data structure <-> XMLRPC translation. Python has both client and server packages in the standard lib. > Then I thought about WSDL. > Would this be the next logical step, or is this more for > allowing different companies to communicate with each other > when there needs to be a broadcast description of the interface? As the name implies, W(eb) S(ervice) D(escription) L(anguage) is meant to describe a given web service - and says nothing about implementation. My 2 cents -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bearophileHUGS at lycos.com Thu Nov 16 19:44:54 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Nov 2006 16:44:54 -0800 Subject: dict.reserve and other tricks Message-ID: <1163724294.126102.216870@e3g2000cwe.googlegroups.com> I have started doing practice creating C extensions for CPython, so here are two ideas I have had, possibly useless. If you keep adding elements to a CPython dict/set, it periodically rebuilds itself. So maybe dict.reserve(n) and a set.reserve(n) methods may help, reserving enough (empty) memory for about n *distinct* keys the programmer wants to add to the dict/set in a short future. I have seen that the the C API of the dicts doesn't allow this, and I don't know if this can be implemented modifying the dicts a bit. Do you think this may be useful? ------------------------------- Sometime I need to remove some elements from dicts/sets. If I know a rule that tells what elements have to be removed I can use code like this: import itertools def filterset(predicate, inset): return set(itertools.ifilter(predicate, inset)) print filterset(lambda x: x & 1, set(range(10))) Output: set([1, 3, 9, 5, 7]) And a similar one to filter dicts that works with a predicate(key, val). Most of the times such functions are good enough, but sometimes the dicts are big, so to reduce memory used I remove keys in place: def filterdict(pred, indict): todel = [k for k,v in indict.iteritems() if not pred(k,v)] for key in todel: del indict[key] d = dict.fromkeys(xrange(8), 0) print d filterdict(lambda k,v: k & 1, d) print d # Output: # {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0} # {1: 0, 3: 0, 5: 0, 7: 0} But doing the same thing while iterating on the dict may be faster and use even less memory. This iteration&deletion capability is probably not safe enough to be used inside Python programs, but a compiled C module with a function that works like that filterdict (and deletes while iterating) may be created, and its use is safe from Python programs. The C++ STL API of maps allows to delete items while iterating on the map (but probably it has to be done only when necessary, because it may be a source for bugs): typedef map isMap; typedef isMap::value_type isValType; typedef isMap::iterator isMapItor; void main() { isMap m; ... // items added to m for(isMapItor itr = m.begin(); itr != m.end();) { if(itr->second == "somestring") m.erase(itr++); else ++itr; } The Python/C API, 7.4.1 Dictionary Objects, says that's not possible with CPython dicts: >The dictionary p should not be mutated during iteration. It is safe (since Python 2.1) to modify the values of the keys as you iterate over the dictionary, but only so long as the set of keys does not change.< Do you think it may be useful to create to create such C filterdict function that deletes while iterating? (To create such function it probably has to bypass the CPython dict API). Bye, bearophile From sven.dahlstrand at gmail.com Thu Nov 9 18:52:39 2006 From: sven.dahlstrand at gmail.com (Sven) Date: 9 Nov 2006 15:52:39 -0800 Subject: urlretrieve get file name In-Reply-To: References: <1163110313.580268.19660@h48g2000cwc.googlegroups.com> Message-ID: <1163116359.787681.31490@m73g2000cwd.googlegroups.com> Hello Gabriel, Thanks for your help, but I'm a guy with no luck. :-) I can't get the file name from response header... On Nov 10, 12:39 am, Gabriel Genellina wrote: > At Thursday 9/11/2006 19:11, Sven wrote: > > >I'm wrestling with the urlretrieve function in the urllib module. I > >want to download a file from a web server and save it locally with the > >same name. The problem is the URL - it's on the form > >http://www.page.com/?download=12345. It doesn't reveal the file name. > >Some hints to point me in the right direction are greatly appreciated.The file name *may* come in the Content-Disposition header (ex: > Content-Disposition: attachment; filename="budget.xls") > Use urlopen to obtain a file-like object; its info() method gives you > those headers. > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! > ?Abr? tu cuenta ya! -http://correo.yahoo.com.ar From egbert.bouwman at hccnet.nl Sun Nov 12 05:20:53 2006 From: egbert.bouwman at hccnet.nl (egbert) Date: Sun, 12 Nov 2006 11:20:53 +0100 Subject: Python as default Lexer in SciTE Message-ID: <20061112102053.GA5304@hccnet.nl> Is it possible to set Python as the default language in SciTE? Not all my python scripts have the .py extension, only the to_be_imported ones. And I use SciTE only for Python. e. -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From paul at boddie.org.uk Fri Nov 10 06:20:31 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Nov 2006 03:20:31 -0800 Subject: Searching for a module to generate GUI events References: <1162990029.409193.246830@b28g2000cwb.googlegroups.com> Message-ID: <1163157631.425155.218460@h48g2000cwc.googlegroups.com> Stephan Kuhagen wrote: > utabintarbo wrote: > > > http://pywinauto.pbwiki.com/ for Win32 > > Thanks for the hint, looks usable. But it seems, there's nothing for X11 and > MacOSX. I didn't thought, that the problem would be so unusual... Searching for "Python GUI testing" on Google gave this as the first result: http://www.redhat.com/magazine/020jun06/features/dogtail/ Comments on similar techniques for OS X can be found here: http://www.oluyede.org/blog/2006/07/04/europython-day-1/ Other X11 projects which might support low-level interactions with applications include the following: http://python-xlib.sourceforge.net/ http://plwm.sourceforge.net/ Paul From SSchukat at dspace.de Wed Nov 15 11:42:36 2006 From: SSchukat at dspace.de (Stefan Schukat) Date: Wed, 15 Nov 2006 17:42:36 +0100 Subject: PyWin32-winxptheme and py2exe In-Reply-To: Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB902318B@exchange2003.dspace.de> You probably need to include the common Control Manifest to supprt themes see in the py2exe\samples\advanced directory for an example how to do it. Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org] On > Behalf Of Andrea Gavana > Sent: Tuesday, November 14, 2006 10:43 PM > To: python-list at python.org > Subject: PyWin32-winxptheme and py2exe > > Hi all, > > I am having some troubles mixing py2exe and winxptheme. > Basically, I am using wxPython 2.7.2.0 with Python 2.5, and > painting some window background using the UxTheme via > winxptheme. This is what I am doing: > > hwnd = MyWindow.GetHandle() > self.hTheme = winxptheme.OpenThemeData(hwnd, "Window") > > winxptheme.DrawThemeBackground(self.hTheme, dc.GetHDC(), 5, 1, > (rc.top, rc.left, rc.right, > rc.bottom), None) > > > This works very well using python directly, but when I > generate and executable file with py2exe, I get this error > when executing that last > line: > > TypeError: an integer is required > > This is because self.hTheme is *None*. It seems like > OpenThemeData can not be initialized in an executable, or at > least that I am not able to do it. > Does anyone have a possible solution to this problem? I have > tried all the possibilities with py2exe, meaning bundle=1, > bundle=2, bundle=3, compressed=1, compressed=2, every > possible combination. But it doesn't work :-( > > I attach my setup file, if it can be of any help. > > Thank you very much for every pointer. > > > -- > Andrea. > > "Imagination Is The Only Weapon In The War Against Reality." > http://xoomer.virgilio.it/infinity77/ > From bearophileHUGS at lycos.com Fri Nov 3 03:29:23 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 3 Nov 2006 00:29:23 -0800 Subject: Defaultdict and speed Message-ID: <1162542563.386682.3090@b28g2000cwb.googlegroups.com> This post sums some things I have written in another Python newsgroup. More than 40% of the times I use defaultdict like this, to count things: >>> from collections import defaultdict as DD >>> s = "abracadabra" >>> d = DD(int) >>> for c in s: d[c] += 1 ... >>> d defaultdict(, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}) But I have seen that if keys are quite sparse, and int() becomes called too much often, then code like this is faster: >>> d = {} >>> for c in s: ... if c in d: d[c] += 1 ... else: d[c] = 1 ... >>> d {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1} So to improve the speed for such special but common situation, the defaultdict can manage the case with default_factory=int in a different and faster way. Bye, bearophile From kay.schluehr at gmx.net Mon Nov 13 09:16:08 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 13 Nov 2006 06:16:08 -0800 Subject: reduce to be removed? In-Reply-To: References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> Message-ID: <1163427368.631537.94820@i42g2000cwa.googlegroups.com> On 12 Nov., 00:14, Fredrik Lundh wrote: > if you care about writing robust code, why not just use a for-loop, > and the list extend method? > > Because generic solutions using HOFs increase abstraction and reduce() the amount of code one has to write even when they are outcasted by Guido? From gagsl-py at yahoo.com.ar Mon Nov 20 18:03:41 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Nov 2006 20:03:41 -0300 Subject: trying to create a dictionary in python, using variables as a value In-Reply-To: <1164008459.159792.48600@k70g2000cwa.googlegroups.com> References: <1164008459.159792.48600@k70g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061120200213.03453550@yahoo.com.ar> At Monday 20/11/2006 04:40, ronrsr wrote: >but I keep getting syntax errors on this one - > >adict = {'zid': result[0][0], 'keywords': result{0][1], >'quotations':result[0][2],'citations':result[0]{3]}; >zhtml.print_update_form(adict); There *are* syntax errors, result{0] should be result[0], and result[0]{3] should be result[0][3] -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From steve at holdenweb.com Tue Nov 14 04:25:22 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Nov 2006 09:25:22 +0000 Subject: Data structure for ordered sequence In-Reply-To: <02d701c707c2$80d8f320$03000080@hendrik> References: <1163410449.081226.49270@i42g2000cwa.googlegroups.com><1163411468.025376.171210@k70g2000cwa.googlegroups.com> <02d701c707c2$80d8f320$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Fredrik Lundh" wrote: > > >> Eric_Dexter at msn.com wrote: >> >> > unless this is homework because the pil people will not let >>> you distribute pils. >> I'm not sure I can parse this sentence fragment. What do you mean? > > oh come on! - you of all people should know that "pils" means mushroom... > Cue yet another appearance of badgerbadgerbadger? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Leo.Kislov at gmail.com Mon Nov 6 15:29:08 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 6 Nov 2006 12:29:08 -0800 Subject: Erronous "unsupported locale setting" ? References: <1162820153.697175.18190@h54g2000cwb.googlegroups.com> Message-ID: <1162844948.123835.311430@f16g2000cwb.googlegroups.com> robert wrote: > Leo Kislov wrote: > > robert wrote: > >> Why can the default locale not be set by its true name? but only by '' ? : > > > > Probably it is just not implemented. But since locale names are system > > specific (For example windows accepts 'ch' as Chinese in Taiwan, where > > as IANA > > considers it Chamorro) setlocale should probably grow an additional > > keyword parameter: setlocale(LC_ALL, iana='de-DE') > > that'd be another fat database to blow up the python core(s). > > I just wonder why locale.setlocale(locale.LC_ALL,"de_DE") doesn't accept the name, which > >>> locale.getlocale() / getdefaultlocale() > ('de_DE', 'cp1252') > already deliver ? It is documented that those functions return cross platform RFC 1766 language code. This code sometimes won't be compatible with OS specific locale name. Cross platform code can useful if you want to create your own locale database for example cross platform language packs. Right now we have: setlocale(category) -- get(it's not a typo) OS locale name getlocale(category) -- get cross platform locale name setlocale(category,'') -- enable default locale, return OS locale name getdefaultlocale() -- get cross platform locale name I agree it's very confusing API, especially setlocale acting like getter, but that's what we have. Improvement is welcome. -- Leo From john106henry at hotmail.com Tue Nov 7 17:42:28 2006 From: john106henry at hotmail.com (John Henry) Date: 7 Nov 2006 14:42:28 -0800 Subject: Pyro stability In-Reply-To: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> Message-ID: <1162939348.273142.6850@m73g2000cwd.googlegroups.com> Being a non-professional programmer, I've managed to use Pyro to do what I need to do with very minimal fuss. In fact, I don't even understand a lot of what's under the cover. All I did was to mimic what one of the sample program is doing and adapted it to my need. So far I am very happy with Pyro. And no, I don't need to use profanity to describe to you how amazing I think Pyro is. :=) writeson wrote: > Hi all, > > At work I'm considering proposing a solution for our distributed > processing system (a web based shopping cart that feeds an actual > printing production line) based on Pyro. I've done some minor > experiments with this and Pyro looks interesting and like a good > implementation of what I want. I've got a couple of questions though: > > 1) Has anyone had any experience with Pyro, and if so, have you had > any stability, or memory use issues running Pyro servers or nameservers > on the various participating computers? (We have a mixed environment of > Linux and Windows, but will be heading to an all Linux (RedHat) > environment soon. > > 2) One of the guys I work with is more inclined to set up XMLRPC > communication between the processes, and he is also leery of running > daemon processes. His solution is to have essentially Python CGI code > that responds to the various XMLRPC requests. Does anyone have any > opinions on this? I know what mine are already. :) > > 3) I've considered using CORBA, which is more powerful, and certainly > faster, but it's complexity to set up compared to the rather simple > work I'm trying to do seems prohibative. Does anyone have any thoughts > on this? > > Thanks in advance, > Doug From exarkun at divmod.com Thu Nov 2 14:15:58 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 2 Nov 2006 14:15:58 -0500 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: Message-ID: <20061102191558.20948.700824158.divmod.quotient.10758@ohm> On Thu, 02 Nov 2006 19:32:54 +0100, robert wrote: >I'd like to use multiple CPU cores for selected time consuming Python computations (incl. numpy/scipy) in a frictionless manner. NumPy releases the GIL in quite a few places. I haven't used scipy much, but I would expect it does too. Are you certain you need this complexity? Jean-Paul From skip at pobox.com Sat Nov 11 19:09:59 2006 From: skip at pobox.com (skip at pobox.com) Date: Sat, 11 Nov 2006 18:09:59 -0600 Subject: explicit self revisited In-Reply-To: <1163288444.893136.42030@h54g2000cwb.googlegroups.com> References: <1163288444.893136.42030@h54g2000cwb.googlegroups.com> Message-ID: <17750.26199.887883.166114@montanaro.dyndns.org> Doug> The explicit self is there simply because OOP was tacked onto Doug> python as an afterthought. Got a reference to support that claim? Skip From fredrik at pythonware.com Mon Nov 13 16:57:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Nov 2006 22:57:14 +0100 Subject: explicit self revisited In-Reply-To: References: <1163407870.637052.32760@m73g2000cwd.googlegroups.com> Message-ID: Peter Maas wrote: > But at least I learned something: a heated debate isn't bound to become an > endless thread if the OP abstains from answering idiot replies ;) trolling is trolling even if you use smilies. I'm sure you can find a way to actually *contribute* to Python if you really want to... From iiu-bounces at iiu.taint.org Sat Nov 11 14:47:26 2006 From: iiu-bounces at iiu.taint.org (iiu-bounces at iiu.taint.org) Date: Sat, 11 Nov 2006 19:47:26 +0000 Subject: Your message to IIU awaits moderator approval Message-ID: Your mail to 'IIU' with the subject Returned mail: Data format error Is being held until the list moderator can review it for approval. The reason it is being held: ClamAV identified this message as a virus (Worm.Mydoom.M) Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://amgod.boxhost.net/cgi-bin/mailman/confirm/iiu/cee7316ed79723da5da0d101a94bae18848168ac From steve at holdenweb.com Sat Nov 4 09:23:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 04 Nov 2006 14:23:32 +0000 Subject: WSDL? In-Reply-To: <32822fe60611040558v511b7ce5v3062279228adcdd@mail.gmail.com> References: <454ba334$0$12110$88260bb3@free.teranews.com> <32822fe60611040558v511b7ce5v3062279228adcdd@mail.gmail.com> Message-ID: Jorge Vargas wrote: > On 11/4/06, Marc 'BlackJack' Rintsch wrote: > >>In , Jorge Vargas >>wrote: >> >> >>>and please please don't go to corba we need to kill that. >> >>Have you real reasons or is this a religious thing? As I see it Corba is >>much better supported by Python libs than SOAP is. >> > > I see ZSI as a very good engine for SOAP as for xmlrpc it's "better" > since you can interact with a browser and then you can even have json > rpc. > > but yes ur right is mostly because of religious reasons :) > When SOAP can do everything that Corba can do, and as efficiently, it might stand a chance of displacing it. I see SOAP as essentially an ugly bloated NIH response of the Microsoft camp to an open specification that achieved all its goals in an elegant way. And all to allow inappropriate remote-method execution through port 80 to avoid the corporate firewall. Which ultimately just made firewalling port 80 that much more difficult. Microsoft is a poor church, and very uncaring of its adherents. So take your religious reasons and leave Corba alone until SOAP is an effective competitor ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From steve at holdenweb.com Wed Nov 1 22:57:45 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Nov 2006 03:57:45 +0000 Subject: CSV module, DictReader problem (bug?) In-Reply-To: <1162434526.601605.315560@k70g2000cwa.googlegroups.com> References: <1162415232.190913.163240@m73g2000cwd.googlegroups.com> <1162434526.601605.315560@k70g2000cwa.googlegroups.com> Message-ID: John Machin wrote: > Tom Plunket wrote: > >>John Machin wrote: >> >> >>>If you were to write 'c:\temp\book1.csv', it would blow up ... because >>>\t -> tab and \b -> backspace. Get into the habit of *always* using raw >>>strings r'C:\Temp\Book1.csv' for Windows file names (and re patterns). >>>You could use double backslashing 'C:\\Temp\\Book1.csv' but it's >>>uglier. >> >>...alternatively you can just use 'unix slashes', e.g. >>'c:/temp/book1.csv', since those work just fine 'cause the Windows >>APIs deal with them properly. > > > Not all APIs do the right thing. If you fire up the cmd.exe shell and > feed it slashes as path separators, it barfs. Example: > C:\junk>dir c:/junk/*.bar > Invalid switch - "junk". > Hence the advice to use rawstrings with backslashes -- they work under > all circumstances. > The command shell is not an API. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bearophileHUGS at lycos.com Fri Nov 17 02:51:36 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Nov 2006 23:51:36 -0800 Subject: dict.reserve and other tricks In-Reply-To: <1163742923.680092.264030@j44g2000cwa.googlegroups.com> References: <1163724294.126102.216870@e3g2000cwe.googlegroups.com> <1163742923.680092.264030@j44g2000cwa.googlegroups.com> Message-ID: <1163749896.776736.201510@h48g2000cwc.googlegroups.com> Thank you for the answers Terry Reedy and Klaas. > Since you are writing extensions, you can create a built-in subclass of > dict to experiment with. I presume the 2.5 default dict should be a model. That way it's doable, but I think it's of limited use too; I'd like to remove elements from arbitrary (normal) dicts. Klaas: > Well, you can reduce the memory usage to virtually nothing by using a > generator expression rather than list comprehension. Are you sure? I don't think so. Can you show a little example? As you know this can't work: def filterdict(pred, indict): todel = (k for k,v in indict.iteritems() if not pred(k,v)) for key in todel: del indict[key] d = dict.fromkeys(xrange(8), 0) print d filterdict(lambda k,v: k & 1, d) print d (You can remove elements from the dict and put them into a list, and then put back the elements into the dict, this is probably the only way I know of *theoretically* keeping the memory used about the same with Python. In practice the less memory consuming version may be the filterdict I have shown). > arbitrary python code can be executed by __hash__ > and deleting (DECREF) python objects. I am starting to understand. I'll think more about this. Thank you, bye, bearophile From sjmachin at lexicon.net Sat Nov 18 02:58:39 2006 From: sjmachin at lexicon.net (John Machin) Date: 17 Nov 2006 23:58:39 -0800 Subject: How can I speed this function up? In-Reply-To: <3Mu7h.67910$rP1.39757@news-server.bigpond.net.au> References: <3Mu7h.67910$rP1.39757@news-server.bigpond.net.au> Message-ID: <1163836719.802864.183650@b28g2000cwb.googlegroups.com> On Nov 18, 2:05 pm, Chris wrote: > with this function I went from 8.04 s to 6.61 s. And your code became less understandable. > Now running up against > my limited knowledge of python. Any chance of getting faster? You have saved 1.4 *seconds*. What is the normal running time for this app with 0.5M records? What is 1.4 seconds as a percentage of that? Please consider that you are barking up the wrong gum tree. Competing with a C app on speed is not something that experienced Python programmers would take on lightly. Talk to your colleague about some of these factors: time to write code, robustness, clarity, ease of maintenance. Cheers, John From markonlinux at internode.on.net Tue Nov 14 04:55:43 2006 From: markonlinux at internode.on.net (Mark Woodward) Date: Tue, 14 Nov 2006 20:55:43 +1100 Subject: Is python for me? References: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> Message-ID: On Mon, 13 Nov 2006 09:11:13 -0800, lennart wrote: > Hi, > > I'm planning to learn a language for 'client' software. Until now, i > 'speak' only some web based languages, like php. As a kid i programmed > in Basic (CP/M, good old days :'-) ) Now i want to start to learn a > (for me) new computer language. > > I like Python. Its free, easy to learn and some favorite programs of my > are written in Python / can understand Python (like OpenOffice) etc. > > But I'm not a full-time programmer. I know, that I've only time & > possibility to learn one (= 1) language good. So i ask myself is python > the language I'm looking for? ... I've been hesitant to write this in the past but seems like a good time. I'm at the same stage, but (and this is NOT a troll) I'm tossing up between Python and Ruby. I know this has been discussed numerous times but I'd like to come at it from a different angle. I've been 'playing' with both languages and to be honest it's a case of 6 of one, half a dozen of the other. If I'm using python I 'think' python and if I'm using Ruby I 'think' ruby (if that makes sense). Ie I don't find I'm more productive in one over the other to any great extent (pretty unproductive in both ATM to be honest ;-)) . In the foreseeable future I suspect I'll stick with one and just use it for things I personally will use/need. But (and here's where I finally get to a question) I use Linux, I love the whole idea of open source and contributing in some way. So if I ever get to the stage where I can give something back is one preferred over the other? I would have thought no but I read on the Ubuntu site somewhere that they prefer contributions written in Python/ pyGTK?? Is this just a 'preference' or because python is installed by default? (whereas Ruby isn't)? Is it just Ubuntu or Linux distros in general? I hope you can see where I'm coming from here. I don't want to start a Python/Ruby flame war. That's not the question. The question is "is one preferred over the other when contributing software and is this just a particular distros preference"? cheers, -- Mark From kib2 at free.fr Fri Nov 24 15:42:50 2006 From: kib2 at free.fr (tool69) Date: Fri, 24 Nov 2006 21:42:50 +0100 Subject: Pydev configuration In-Reply-To: <1164389878.833569.60710@l39g2000cwd.googlegroups.com> References: <1164389878.833569.60710@l39g2000cwd.googlegroups.com> Message-ID: <456757c2$0$7958$426a74cc@news.free.fr> S?bastien Boisg?rault a ?crit : > Hi, > > Did anyone managed to change the code font family/size > in Pydev (Python Editor Plugin for Eclipse) ? I found how > to change the color mapping (Windows/Preference/Pydev) > but did not found the font setting. > > Cheers, > > SB > Salut S?bastien, Preferences/General/Appearence/Colors&Fonts/ in the right menu choose Basic/Text Font 6TooL9 From WeikEngOff at aol.com Wed Nov 15 12:21:30 2006 From: WeikEngOff at aol.com (Udo) Date: 15 Nov 2006 09:21:30 -0800 Subject: Editor w. Code Completion for COM-Libs (ActivePython 2.3) Message-ID: <1163611290.132982.317010@k70g2000cwa.googlegroups.com> Hello, I'm looking for an Python-editor which supports code completion for imported COM-Libs. I'm using ActivePython 2.3. Any hints? Thanks and kind regards Udo From __peter__ at web.de Wed Nov 8 16:08:47 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Nov 2006 22:08:47 +0100 Subject: is this the right way to do subclasses? References: <45522074$0$17101$c3e8da3@news.astraweb.com> <45523133$0$14421$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Peter Otten wrote: > >> One way to avoid the repetition: >> >> class Character(object): >> def __init__(self, name, strength, dexterity, intelligence): >> self.name = name >> self.health = 10 >> self.strength = strength >> self.dexterity = dexterity >> self.intelligence = intelligence >> self.fix_attributes() >> >> class Fighter(Character): >> def fix_attributes(self): >> self.health += 2 >> self.strength += 1 >> >> You may need a no-op implementation of fix_attributes() in the Character >> class. > But how does this take care of the initialization of the stats? I won't > be able to use Fighter to create a character without doing everything in > Character, right? Try it: Fighter(...) will implicitly call Character.__init__(...). Peter From bj_666 at gmx.net Thu Nov 9 03:15:11 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 09 Nov 2006 09:15:11 +0100 Subject: profanity on comp.lang.python (was Re: Pyro stability) References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> <87slgt1vmh.fsf@gmail.com> <4552723b$0$323$e4fe514c@news.xs4all.nl> Message-ID: In , skip wrote: > > Irmen> So there. Finally back on the original subject ;-) > > And without satisfying Godwin's Law. Pretty good. Which was very hard with all those language nazis out there. Ooops? SCNR, Marc 'BlackJack' Rintsch From Leo.Kislov at gmail.com Tue Nov 28 06:26:04 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 28 Nov 2006 03:26:04 -0800 Subject: Modifying every alternate element of a sequence References: <1164710289.544394.101170@h54g2000cwb.googlegroups.com> Message-ID: <1164713164.043283.161370@l39g2000cwd.googlegroups.com> jm.suresh at no.spam.gmail.com wrote: > I have a list of numbers and I want to build another list with every > second element multiplied by -1. > > input = [1,2,3,4,5,6] > wanted = [1,-2,3,-4,5,-6] > > I can implement it like this: > > input = range(3,12) > wanted = [] > for (i,v) in enumerate(input): > if i%2 == 0: > wanted.append(v) > else: > wanted.append(-v) > > But is there any other better way to do this. Use slices: input[1::2] = [-item for item in input[1::2]] If you don't want to do it in-place, just make a copy: wanted = input[:] wanted[1::2] = [-item for item in wanted[1::2]] -- Leo From ask at me Wed Nov 1 23:55:14 2006 From: ask at me (alf) Date: Wed, 01 Nov 2006 22:55:14 -0600 Subject: Python images processing -recap Message-ID: Hi, I try to summarize what is available in python for graphical images processing. So far I found: -PythonMagic -PIL -SDL_image Are all supported, which is most mature, in which I could perform for instance 'Ken Burns effect' or light filling operations. Is there anything else? -- alf From skip at pobox.com Fri Nov 10 23:41:53 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 10 Nov 2006 22:41:53 -0600 Subject: mushrooms are animals? [was Re: Py3K idea: why not drop the colon?] In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> Message-ID: <17749.21649.286856.219920@montanaro.dyndns.org> Steven> The world seems to be flat, the sun appears to rotate around the Steven> Earth, and mushrooms look like they are more closely related to Steven> plants than to animals, but none of these things are actually Steven> the case. Where can I read about mushrooms as animals? Skip From Leo.Kislov at gmail.com Mon Nov 13 06:23:35 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 13 Nov 2006 03:23:35 -0800 Subject: str.title question after ' References: Message-ID: <1163417015.047332.197000@m73g2000cwd.googlegroups.com> Antoon Pardon wrote: > I have a text in ascii. I use the ' for an apostroph. The problem is > this gives problems with the title method. I don't want letters > after a ' to be uppercased. Here are some examples: > > argument result expected > > 't smidje 'T Smidje 't Smidje > na'ama Na'Ama Na'ama > al pi tnu'at Al Pi Tnu'At Al Pi Tnu'at > > > Is there an easy way to get what I want? def title_words(s): words = re.split('(\s+)', s) return ''.join(word[0:1].upper()+word[1:] for word in words) > > Should the current behaviour condidered a bug? I believe it follows definition of \w from re module. > My would be inclined to answer yes, but that may be > because this behaviour would be wrong in Dutch. I'm > not so sure about english. The problem is more complicated. First of all, why title() should be limited to human languages? What about programming languages? Is "bar.bar.spam" three tokens or one in a foo programming language? There are some problems with human languages too: how are you going to process "out-of-the-box" and "italian-american"? -- Leo From bblais at bryant.edu Fri Nov 3 12:29:20 2006 From: bblais at bryant.edu (Brian Blais) Date: Fri, 03 Nov 2006 12:29:20 -0500 Subject: setting up wxPython on a Mac In-Reply-To: <454B6DB4.4040107@kevin-walzer.com> References: <454B6DB4.4040107@kevin-walzer.com> Message-ID: <454B7C70.7050402@bryant.edu> Kevin Walzer wrote: > Brian Blais wrote: >> Hello, >> >> I have a wxPython program that I would like to give to a friend of mine >> who has a Mac. Is there a resource out there that can tell me what >> steps I need to follow to do this? >> > Install Python from the Python website--a Python 2.5 installer is > available for the Mac. > > Install wxPython from the wxPython website--an installer for the latest > version of wxPython for the Mac is also available. > > That should do it. > sounds easy. If I need the numpy/scipy/matplotlib combo, is it that straightforward? On windows it is, on Linux is definitely is not. thanks, bb -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From jameshcunningham at gmail.com Wed Nov 15 23:04:56 2006 From: jameshcunningham at gmail.com (James Cunningham) Date: Wed, 15 Nov 2006 23:04:56 -0500 Subject: Python v PHP: fair comparison? References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> <1163605059.270769.293290@m73g2000cwd.googlegroups.com> <455baf21$0$28561$426a74cc@news.free.fr> <1163642366.698784.130390@i42g2000cwa.googlegroups.com> Message-ID: <2006111523045616807-jameshcunningham@gmailcom> On 2006-11-15 20:59:26 -0500, "walterbyrd" said: > > Bruno Desthuilliers wrote: >> walterbyrd a ?crit : > >> You mean there are web hosting companies that are still using Apache >> 1.3.x ? >> > > Practically all web-hosters still use Apache 1.3.x. Certainly all of > the lower priced hosters. Not true. Dreamhost, at least, uses Apache 2. > >> C'mon, let's be serious. I just ordered a dedibox - a small dedicated >> web server - for my personal use. It's only 30 euros a month, you know... > > What if I only need 25mb of space? I can that with a PHP hoster for $10 > a year. That is about 1/36th the price that you posting about. > > Maybe you don't mind paying 30 euros a month, but a lot others do. Of course, you can't get $10 a year plans on Dreamhost. But with deals you can get it down to about that low, at least for the first year. I suppose I'm lucky enough not to miss $8 a month otherwise. Best, James From phil at riverbankcomputing.co.uk Sun Nov 5 17:23:06 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 5 Nov 2006 22:23:06 +0000 Subject: ANN: PyQt v4.1 Released In-Reply-To: <1162749608.733730.321970@k70g2000cwa.googlegroups.com> References: <1162749608.733730.321970@k70g2000cwa.googlegroups.com> Message-ID: <200611052223.06388.phil@riverbankcomputing.co.uk> On Sunday 05 November 2006 6:00 pm, vj wrote: > > Riverbank Computing is pleased to announce the release of PyQt v4.1 > > available from http://www.riverbankcomputing.co.uk/pyqt/. > > What's the best way to learn pyqt. Do the examples from the book GUI > Programming with Python: QT Edition still work? Is the material from > the book mostly valid or have things changed quite a bit? > > http://www.commandprompt.com/community/pyqt/ The basics haven't changed, but Qt v4 covers many more things than Qt v2. I think it's still perfectly valid for the basics - but API differences probably mean the examples need some changes. Phil From 2Shreekar at gmail.com Thu Nov 2 10:26:52 2006 From: 2Shreekar at gmail.com (Shreekar Patel) Date: 2 Nov 2006 07:26:52 -0800 Subject: is mod_python borked? In-Reply-To: <1162480110.992783.267620@e3g2000cwe.googlegroups.com> References: <1162480110.992783.267620@e3g2000cwe.googlegroups.com> Message-ID: <1162481212.495984.101510@m73g2000cwd.googlegroups.com> walterbyrd wrote: > I am considering python, instead of php, for web-application > development. I often see mod_python.criticisized as being borked, > broken, or just plain sucking. > > Any truth to any of that? No, I've been using mod_python for a long time, and I haven't run in to any problems. In fact I use python server pages for my web development, which is much faster than python cgi scripts. http://vsbabu.org/webdev/pydev/python10.html Once you set up your server for psp pages, it's so easy. Very similar to php pages. Just give it a go and you'll like it. http://www.modpython.org/ for setting up server with mod_python. From Mythmon at gmail.com Sat Nov 11 15:28:05 2006 From: Mythmon at gmail.com (Mythmon at gmail.com) Date: 11 Nov 2006 12:28:05 -0800 Subject: Why does this code crash python? In-Reply-To: <4556246a$0$326$e4fe514c@news.xs4all.nl> References: <1163272625.991469.153870@i42g2000cwa.googlegroups.com> <4556246a$0$326$e4fe514c@news.xs4all.nl> Message-ID: <1163276885.609160.163090@h54g2000cwb.googlegroups.com> On Nov 11, 11:28 am, Irmen de Jong wrote: > You're creating a console object "c" and use it in both threads. > > Try creating the console object for each thread by itself, > i.e. remove the global "c = Console.getconsole()" and replace > it by a getconsole() inside each thread class. > > I don't have the Console module so I don't know if it fixes things > for you, but give it a try :) Well, I tried that, and it did something. It made it so the space bar switched the clock once, but not a second time. And it still crashed, but not always at the same time, sometimes it would do it the second time I hit the space bar, sometimes before I hit it the first time, but always when i did something that would generate a Console event (moving the mouse or something). So, I thought it had something to do with Console not working well with threads, so I took it completely out of threads and had just the event checking loop run by itself, and it still crashed. So apparently I am using the Console events wrong. I am going to try and find some examples online on how to watch for events with it, but if worse comes to worse I can try and use keyboard hooks, I've looked at those before, and they might work better. --Mythmon From cjames at callone.net Tue Nov 21 14:42:55 2006 From: cjames at callone.net (c james) Date: Tue, 21 Nov 2006 13:42:55 -0600 Subject: Why is class decorator on method loosing self? In-Reply-To: <1164135863.270437.80340@b28g2000cwb.googlegroups.com> References: <1164135863.270437.80340@b28g2000cwb.googlegroups.com> Message-ID: If I am reading this correctly you, are rebinding min_max in CustomizeMeta using '__customize' as the attribute to identify the member to work on. Thank you. I think you are right, this is probably the best way to implement what I intend for caching resource intensive processing. to George Sakkis wrote: > > I don't think you can make it work without resorting to metaclass > magic. At the point of decoration min_max is still a function, not a > method, because class Foo has not been created yet. Here's a way to do > it with a custom metaclass; whether you really want to do it is a > different matter: > > George > From gagsl-py at yahoo.com.ar Thu Nov 16 20:57:50 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 16 Nov 2006 22:57:50 -0300 Subject: cPickle problems In-Reply-To: <1163724509.572724.199720@f16g2000cwb.googlegroups.com> References: <1163722893.992949.295350@b28g2000cwb.googlegroups.com> <1163723175.530850.185990@m73g2000cwd.googlegroups.com> <1163724509.572724.199720@f16g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061116225442.03fcf748@yahoo.com.ar> At Thursday 16/11/2006 21:48, Jeff Poole wrote: > File "/usr/lib/python2.4/pickle.py", line 313, in save > rv = reduce(self.proto) > File "/usr/lib/python2.4/copy_reg.py", line 83, in _reduce_ex > dict = getstate() >TypeError: 'str' object is not callable Someway, self.__getstate__ is a string, not a method... Since it fails inside a python module, you could print some debug information to see what happens, like repr(self), type(self), repr(getstate)... -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From fredrik at pythonware.com Wed Nov 29 13:11:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Nov 2006 19:11:35 +0100 Subject: Surprise with special floating point values In-Reply-To: <1164822818.252321.132680@j72g2000cwa.googlegroups.com> References: <1164822818.252321.132680@j72g2000cwa.googlegroups.com> Message-ID: prouleau001 at gmail.com wrote: > While trying to use simplejson under Python 2.4.3 I have been > investigating the handling of special floating point values note that JSON doesn't support non-numeric floating point values, as can be seen by the "number" syntax description on this page: http://www.json.org/ (and as I pointed out in another thread on this topic, Python relies on the C library for serialization of floats, so non-numeric floating point values aren't portable between Python versions either). From horpner at yahoo.com Fri Nov 10 11:49:18 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Nov 2006 17:49:18 +0100 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> <4rjlkqFrlskqU1@mid.individual.net> Message-ID: On 2006-11-10, Bjoern Schliessmann wrote: > Neil Cerutti wrote: >> On 2006-11-09, Bjoern Schliessmann > >>> if color == red or blue or green: >>> return 'primary' >>> >>>:) > >> The Inform 6* programming language supports the serial 'or' (and >> 'and') and looks just like that. > > Python also supports it. > >> The disadvantage is that the usual binary logical operators >> must exist and are spelled differently. (It uses C's '||' and >> '&&'.) > > Do they have to be spelled differently? In Python, they don't > have to. That kind of answers your question. ;-) That is cool. I was unaware of the feature; until just now I thought Inform was had innovated the syntax! -- Neil Cerutti From szport at gmail.com Tue Nov 21 16:21:52 2006 From: szport at gmail.com (szport at gmail.com) Date: 21 Nov 2006 13:21:52 -0800 Subject: Note about getattr and '.' Message-ID: <1164144112.686480.60240@j44g2000cwa.googlegroups.com> There is an interesting skewness in python: class A(object): pass >>> a=A() >>> setattr(a, '$foo', 17) >>> getattr(a, '$foo') 17 But I can't write >>> a.'$foo' From shane at hathawaymix.org Tue Nov 7 16:36:05 2006 From: shane at hathawaymix.org (Shane Hathaway) Date: Tue, 07 Nov 2006 14:36:05 -0700 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: Message-ID: <4550FC45.6010500@hathawaymix.org> robert wrote: > I'd like to use multiple CPU cores for selected time consuming Python > computations (incl. numpy/scipy) in a frictionless manner. > > Interprocess communication is tedious and out of question, so I > thought about simply using a more Python interpreter instances > (Py_NewInterpreter) with extra GIL in the same process. I expect to > be able to directly push around Python Object-Trees between the 2 (or > more) interpreters by doing some careful locking. > > Any hope to come through? If possible, what are the main dangers? Is > there an example / guideline around for that task? - using ctypes or > so. > > Or is there even a ready made Python module which makes it easy to > setup and deal with extra Interpreter instances? If not, would it be > an idea to create such thing in the Python std libs to make Python > multi-processor-ready. I guess Python will always have a GIL - > otherwise it would loose lots of comfort in threaded programming I'd like to mention mod_python, which creates multiple interpreters inside Apache. It does this transparently and works well. There is no apparent lock contention between the interpreters, because no Python objects are shared. Also, I'd like to make the observation that it is not always necessary to share the entire interpreter (ala threads) in order to take advantage of multiple cores. I think Python only needs a nice way to share a relatively small set of objects using shared memory. POSH goes in that direction, but I don't think it's simple enough yet. http://modpython.org/ http://poshmodule.sourceforge.net/ Shane From mike.klaas at gmail.com Fri Nov 3 23:46:33 2006 From: mike.klaas at gmail.com (Klaas) Date: 3 Nov 2006 20:46:33 -0800 Subject: Javascript is turning into Python?! In-Reply-To: <7xr6wkt6a3.fsf@ruckus.brouhaha.com> References: <7xslh1dmgt.fsf_-_@ruckus.brouhaha.com> <1162596267.518634.164170@h54g2000cwb.googlegroups.com> <7xr6wkt6a3.fsf@ruckus.brouhaha.com> Message-ID: <1162615592.955299.54130@k70g2000cwa.googlegroups.com> Paul Rubin wrote: > "Carl Banks" writes: > > > http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7 > > Maybe in exchange, Python can borrow the let statement. > > Maybe the with statement could be extended to allow binding more than > one variable. > with x as f(), y as g(): > blah (x, y) from contextlib import nested with nested(f(), g()) as (x, y): .... -Mike From sjmachin at lexicon.net Thu Nov 9 06:31:02 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Nov 2006 03:31:02 -0800 Subject: substring search without using built in utils In-Reply-To: <45530805$0$10013$426a74cc@news.free.fr> References: <45530805$0$10013$426a74cc@news.free.fr> Message-ID: <1163071862.056378.13870@f16g2000cwb.googlegroups.com> Bruno Desthuilliers wrote: > Gabriel Genellina wrote: > > At Wednesday 8/11/2006 22:29, zeal elite wrote: > > > >> I am looking for substring search python program without using the > >> built in funtions like find, or 'in'. > > > > The only reasonable usage for such a constraint would be a school > > assignment so: don't cheat and do your homework! > > > > OTHO, looking for existing solutions to a same or similar problem and > studying them is usually considerer good practice in real-life > programming jobs !-) > Looking at an existing solution for substring search that was coded in Python, instead of using the built-in functionality would IMHO be considered extremely bad practice in a real-life programming job. From matthew at agrip.org.uk Sun Nov 26 13:26:05 2006 From: matthew at agrip.org.uk (Matthew Tylee Atkinson) Date: Sun, 26 Nov 2006 18:26:05 +0000 (UTC) Subject: Persistent Threads & Synchronisation References: Message-ID: On Sun, 26 Nov 2006 13:24:21 +0100, Marc 'BlackJack' Rintsch wrote: > There seems to be a misunderstanding of threads. You don't call functions > in a thread from the main program. If you call a function from the main > thread then the function is executed in the main thread. That's true for > any call on `Thread` objects except for `start()` which really starts > executing the `run()` method in a separate thread. Aha, thanks very much for this! > The easiest way for safe communication with threads is a `Queue` like > the one in the `Queue` module. If you want a download thread that > is running alongside the main program all the time then write a while loop > that gets "commands" via a queue. Something like: Brilliant! I will try it out soon. Thanks very much for your help; it has really explained a lot! best regards, -- Matthew Tylee Atkinson From pavlovevidence at gmail.com Thu Nov 23 21:11:49 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 23 Nov 2006 18:11:49 -0800 Subject: What's going on here? In-Reply-To: References: Message-ID: <1164334309.703616.45790@45g2000cws.googlegroups.com> Dale Strickland-Clark wrote: > Thanks for the answers. I am informed but I don't feel enlightened. > > It does strike me as odd that an apparently empty subclass should add extra > function to the base class. > > Not at all obvious. Remember that a class definition is syntax sugar for a direct call to type: type(name,bases,clsdict) This constructs and returns the class. It's free to add behaviors even if the clsdict is empty, and that's exactly what it does in this case. type considers the absence of __slots__ in clsdict to be a request for an instance dict, and so it adds one. (Types defined in C aren't created that way, however. I believe C-defined types request an instance dict by reserving space for it in the object structure and setting tp_dictoffset to indicate its offset.) This is not obvious, but it's really the only reasonable way. You can't have the base class of all objects creating dicts for its instances--you wouldn't want every int object to have it's own dict. And you can't have Python class instances not have a dict by default. Carl Banks From news at p2b.datatailors.com Thu Nov 9 06:31:11 2006 From: news at p2b.datatailors.com (Peter van Kampen) Date: 09 Nov 2006 11:31:11 GMT Subject: Is there a commas-in-between idiom? References: Message-ID: On 2006-11-08, Georg Brandl wrote: > Peter van Kampen schrieb: >> On 2006-11-06, Fredrik Lundh wrote: >>> I've collected a bunch of list pydioms and other notes here: >>> >>> http://effbot.org/zone/python-list.htm >> >> """ >> A = B = [] # both names will point to the same list >> """ >> >> I've been bitten by this once or twice in the past, but I have always >> wondered what it was useful for? Can anybody enlighten me? > > Do you never have a situation where you want to assign the same value > to two variables? In the sense that I might want two empty lists or maybe 2 ints that are initialised as 0 (zero). That's what I (incorrectly) thought A = B = [] did. > Or are you objecting to the fact that both names point to the same > object? I'm not objecting to anything, merely wondering when I could/should use this idiom. There's a nice example in another response (self.items = items = []) > It couldn't be otherwise. Consider: > > X = [] > A = B = X > > What should this do? Copy "X" and assign one copy to A, one to B? Ah yes, I see the error in my ways...I skipped the A = B part too lightly. Thanks, PterK -- Peter van Kampen pterk -- at -- datatailors.com From john106henry at hotmail.com Thu Nov 30 14:16:24 2006 From: john106henry at hotmail.com (John Henry) Date: 30 Nov 2006 11:16:24 -0800 Subject: Is there an easier way to express this list slicing? In-Reply-To: References: <1164913125.509492.54060@79g2000cws.googlegroups.com> Message-ID: <1164914184.104754.266670@j72g2000cwa.googlegroups.com> Well, pardoon me. Next. Thomas Ploch wrote: > John Henry schrieb: > > If I have a list of say, 10 elements and I need to slice it into > > irregular size list, I would have to create a bunch of temporary > > variables and then regroup them afterwords, like: > > > > # Just for illustration. Alist can be any existing 10 element list > > a_list=("",)*10 > > (a,b,c1,c2,c3,d1,d2,d3,d4,d5)=a_list > > alist=(a,) > > blist=(b,) > > clist=(c1,c2,c3) > > dlist=(d2,d3,d4,d5) > > > > That obviously work but do I *really* have to do that? > > > > BTW: I know you can do: > > alist=a_list[0] > > blist=a_list[1] > > clist=a_list[2:5] > > dlist=a_list[5:] > > > > but I don't see that it's any better. > > > > Can I say something to the effect of: > > > > (a,b,c[0:2],d[0:5])=a_list # Obviously this won't work > > > > ?? > > > > I am asking this because I have a section of code that contains *lots* > > of things like this. It makes the code very unreadable. > > > > Thanks, > > > > Nothing in your code actually __is__ a list. they are all tuples... > A list is: > aList = [a,b,c1,c2,c3,d1,d2,d3,d4,d5] > > Thomas From mail at microcorp.co.za Sun Nov 5 03:12:01 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 5 Nov 2006 10:12:01 +0200 Subject: Programming Language that is Spreadsheet/Table Based References: <1162588208.533235.266100@k70g2000cwa.googlegroups.com><1162626260.236167.157920@m73g2000cwd.googlegroups.com><1162638585.016404.20270@m7g2000cwm.googlegroups.com> Message-ID: <012501c700b2$12ef4d80$03000080@hendrik> "James Stroud" wrote: > Gerard Flanagan wrote: 8<---------------------------------------------- > Thank you, this is very good stuff to think about. > > James I can't really add to the above train of thought... And I don't know if this will help - but if you want to think, here is a skewed, simple view: If I were to try and do something like this, I would start by defining a spread sheet like dict to keep everything in, using (column,row) tuples as keys, and build on top of that. This would give you the ability to keep *anything* in a cell, and the database like structures you are thinking of would live on top of this underlying access structure, with the (column,row) being a direct *pointer* to an element in one fast step. I would then also use other dicts to describe what is kept in the "columns" - something simple like: header_dict = {0:['name of person','Name','Enter your name'],1:['age of person since birth','Age','Enter your birthday'], ... } where the first item in the list is a help string, the second a column header for printing, the third the string to use as prompt for a GUI, etc... - you could even keep and enforce type if you wanted to - must be int, must be date, column width for printing, validation data and rules, - whatever. In a sense this is a sort of inverted way of looking at a file - instead of having an underlying dict with (column, row) keys, you could alternatively have "loose" column dicts only to keep the data in ( note that I have been writing (column, row) consistently, instead of the more conventional (row,column).) - this would make adding or deleting columns almost trivial. You *could* also have references to Python functions or class methods living alongside the data in the cells, and then things can get hairy - for an age entry, for instance, the cell can look like: Data[(column,row)] = # (or Age[row] in the alternative approach) [(1947,01,24),self.BirthdayChecker,self.PresentChooser,self.LetterWriter, ...] where the first entry, the tuple, represents the data (could have been a list or dict, of course ) and the rest are methods or functions to use, in this particular instance. You could instead have these function references in the age column's header dict entry, for those of them that have applicability across all rows of the column, just like the idea of type enforcement or validation above. For a kind of row, or row type, you need then simply keep a list of column numbers that are required for this "record", with a different list defining a different record type - Gold members need these column entries filled in, while Silver members need only those... simple, but then you need a record type column... This sort of thing organises the stuff, but the code to use it becomes a bit impenetrable, as you have to write a kind of crawling process to access the structure to do what is required, but it is all "table driven" and can be very flexible. Its not a weekend project though, and when you are finished its a kind of super relational database... HTH - Hendrik From fabiofz at gmail.com Wed Nov 1 07:00:57 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 1 Nov 2006 09:00:57 -0300 Subject: Pydev 1.2.5 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.2.5 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: ----------------------------------------------------------------- * Minor bug on mark occurrences fixed * The quick outline now will go to the 'sole item' in the tree even if it is not selected (and OK is pressed) Release Highlights in Pydev: ---------------------------------------------- * Early release of the Pydev package explorer View. Features already implemented: o Common resource actions (delete, copy, rename, team...) o Shows the Source folder with a different icon o Linking mode enabled o Shows the outline for a python file o Opening an item in the outline opens the correct place in the correspondent file o NOTE: The package explorer is still in a beta state * Debugger bug-fix: Crash when debugging wxPython programs should not happen anymore * When opening a file, the encoding is considered (and not only when saving it) * Patches from Gergely Kis: o Option for having a 'default interpreter' in the combo for selecting which interpreter to use for a run o Saving the things related to the pydev project in a .pydevproject file to be commited * Patch from Gregory Golberg: o Ctrl+Shift+D when a variable is selected in debug mode shows the variable value 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 aahz at pythoncraft.com Wed Nov 8 14:18:09 2006 From: aahz at pythoncraft.com (Aahz) Date: 8 Nov 2006 11:18:09 -0800 Subject: profanity on comp.lang.python (was Re: Pyro stability) References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> Message-ID: In article , wrote: > > Beliavsky> English is a rich language, and there are better ways of > Beliavsky> doing that. > > aahz> Oh, gimme a fucking break. > >I'm with Beliavsky on this one. I can't see any particular reason to curse >in a forum such as c.l.py. It just coarsens the discussion with no obvious >positive benefit as far as I can see. Actually, I do agree that profanity "should" be avoided on c.l.py; what I disagree with rather vociferously is having language police like Beliavsky. I consider Beliavsky's offense far worse than the original post. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 1993 From vinjvinj at gmail.com Sat Nov 4 20:42:09 2006 From: vinjvinj at gmail.com (vj) Date: 4 Nov 2006 17:42:09 -0800 Subject: wing ide vs. komodo? In-Reply-To: <2nRXg.108$1n3.2866@news.tufts.edu> References: <2nRXg.108$1n3.2866@news.tufts.edu> Message-ID: <1162690929.501897.258360@b28g2000cwb.googlegroups.com> I've tried both and find WingIDE much faster than Komodo and the layout is very well thought out. I love the way you can collapse all the differnet panes with a few keystrokes. I also like their autocomplete functionality. Wing is developed by a small company, focussed on python development, while komodo supports all the major scripting languages. VJ From st911 at rock.com Thu Nov 30 11:46:04 2006 From: st911 at rock.com (st911 at rock.com) Date: 30 Nov 2006 08:46:04 -0800 Subject: *** ARE The FBI Bastards are making movies of YOUR PRIVATE MARITAL SEXUAL MOMENTS *** Message-ID: <1164905164.126750.305180@j72g2000cwa.googlegroups.com> The written apology reads: "The United States of America apologizes to Mr. Brandon Mayfield and his family for the suffering caused by the FBI's misidentification of Mr. Mayfield's fingerprint and the resulting investigation of Mr. Mayfield, including his arrest as a material witness in connection with the 2004 Madrid train bombings and the execution of search warrants and other court orders in the Mayfield family home and in Mr. Mayfield's law office." He and his family later sued the U.S. government for damages. "We lived in 1984," Mayfield told reporters Wednesday. "I'm talking about the George Orwell, frightening brave new world in which Big Brother is constantly watching you." (Watch Mayfield discuss the case Video) "I, myself, have dark memories of stifling paranoia, of being monitored, followed, watched, tracked," he said, choking back emotion. "I've been surveilled, followed, targeted primarily because I've been an outspoken critic of this administration and doing my job to defend others who can't defend themselves, to give them their day in court, and mostly for being a Muslim." The government refused, he said, to tell him where they put their cameras and surveillance devices, leaving his family wondering if their private conversations and intimate moments were on display. "The days and weeks and months following my arrest were some of the hardest and darkest that myself and my family have ever had to endure," he said. "And all because of this government's ill-conceived war on terror. ... What I really want is for this not to happen to anyone else." Wednesday's settlement includes not only a $2 million payment and an apology, but also an agreement by the government to destroy communications intercepts conducted by the FBI against Mayfield's home and office during the investigation. The written apology reads: "The United States of America apologizes to Mr. Brandon Mayfield and his family for the suffering caused by the FBI's misidentification of Mr. Mayfield's fingerprint and the resulting investigation of Mr. Mayfield, including his arrest as a material witness in connection with the 2004 Madrid train bombings and the execution of search warrants and other court orders in the Mayfield family home and in Mr. Mayfield's law office." A Justice Department statement released Wednesday said Mayfield was not targeted because of his Muslim faith and that the FBI had taken steps to improve its fingerprint identification process "to ensure that what happened to Mr. Mayfield does not happen again." "Mr. Mayfield and his family felt it was in their best interest to get on with their lives," said Mayfield's attorney, Elden Rosenthal. "No amount of money can compensate Mr. Mayfield for being held as a prisoner and being told he faced the death penalty [for the Madrid bombings]." Mayfield said his suit was not about money. "It's about regaining our civil rights, our freedom and most important, our privacy," he said. He and his attorneys said the settlement will allow him to continue the portion of his lawsuit challenging the constitutionality of the Patriot Act. Mayfield contends that his home was searched under provisions of the Patriot Act. ==================================================================== Criminal, Rogue and RACIST elements have penetrated all the branches of USA and world governments. We know that on 911 FBI bastards ran all over in the neighborhood of Pentagon trying to confiscate EVIDENCE of the 911 crime that no Boeing Passenger Airliner hit Pentagon. They have stil not released the evidence. 911 was inside job. FBI is the BEST of the criminal branches ... THERE ARE MORE EVIL AND BIGGER ROGUES IN CIA, NSA, Mossad, PENTAGON AND THE WHITE HOUSE. Dont forget that BASTARD, NIXON and JOHNSON who sank USS LIBERTY and KILLED AMERICANS with the help of ISRAEL ... FBI is the BEST of the criminal branches ... THERE ARE MORE EVIL AND BIGGER ROGUES IN CIA, NSA, PENTAGON AND THE WHITE HOUSE. Dont forget that BASTARD, NIXON and JOHNSON who sank USS LIBERTY and KILLED AMERICANS with the help of ISRAEL ... THE ONLY ONLY REASON FBI DID THIS IS BECAUSE THEIR CRIME WAS UNCONCEALABLE. UNDER THE PRETEXT OF SELF-DEFENSE, MANY OF THESE AGENCY OFFICIALS HAVE COVERED THEIR CRIMES AND DESTROYED EVIDENCE OF THEIR CRIMES. FBI COVERED UP A CHILD PEDOPHILIA RING THAT WAS LINED TO REAGAN AND HERBERT WALKER BUSH. There is a VIDEO on google of the investigation. From cito at online.de Wed Nov 22 14:59:05 2006 From: cito at online.de (Christoph Zwerschke) Date: Wed, 22 Nov 2006 20:59:05 +0100 Subject: Protecting against SQL injection In-Reply-To: References: Message-ID: Tor Erik Soenvisen wrote: > How safe is the following code against SQL injection: > > # Get user privilege > digest = sha.new(pw).hexdigest() > # Protect against SQL injection by escaping quotes > uname = uname.replace("'", "''") > sql = 'SELECT privilege FROM staff WHERE ' + \ > 'username=\'%s\' AND password=\'%s\'' % (uname, digest) > res = self.oraDB.query(sql) This is definitely *not* safe. For instance, set uname = r"\' or 1=1 --" You must replace the backslash with a double backslash as well. But as already suggested, you should better use query parameters. -- Christoph From deets at nospam.web.de Mon Nov 20 09:30:33 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 20 Nov 2006 15:30:33 +0100 Subject: to ask an container instance to suicide References: <1164015742.696913.283050@m73g2000cwd.googlegroups.com> Message-ID: <4sdsg9Fup048U1@mid.uni-berlin.de> jm.suresh at no.spam.gmail.com wrote: > Hi, > I have containers to hold geometrical objects. The members in these > containers can again be containers them self. Now, In the program I > would be moving objects from one container to another. In this process, > If the number of members in one of the containers becomes just one, I > want to delete that container and have only its only member in place of > it in the parent container. > I have implemented setting and getting the container members using > property(). > > Right now, I am planning to do this this way: > Maintain a reference to parent container in each container. > When the condition is detected, do self.parent.deleteObject(self) . > > def deleteObject(self,memberId): > index = self._members.index(memberId) > self._members[index] = memberId._members[0] > del memberId > > Will this work. Or is there any other simple way to do this? I wouldn't implement it this way. I'd rather have a reducer in place - it is benefitial to have a way of visiting you tree of objects. Then you could employ a reducing-scheme that will replace childnodes of a node with their single child as optimization. Diez From anderslanglands at gmail.com Wed Nov 22 07:37:06 2006 From: anderslanglands at gmail.com (anders) Date: 22 Nov 2006 04:37:06 -0800 Subject: PyQt app in seperate thread Message-ID: <1164199026.728638.180000@j44g2000cwa.googlegroups.com> I am writing a plugin for a piece of software in python, and I want to start up a PyQt GUI in the plugin, without stalling the main thread while the gui is running (later i will want to pass messages between the main thread and the gui thread). I'm new to pyqt, so I'm probably doing something very silly, but for the moment I'm just trying to get the first pyqt tutorial example running in a seperate thread: ----8<-------- import sys from PyQt4 import QtGui from PyQt4 import QtCore class MyThread( QtCore.QThread ): def __init__( self ): QtCore.QThread.__init__( self ) def run( self ): app = QtGui.QApplication( sys.argv ) hello = QtGui.QPushButton( 'Hello world!' ) hello.resize( 500, 500 ) hello.show() app.exec_() QtCore.QThread.terminate( ) mt = MyThread() mt.start() print 'Main thread continuing...' mt.wait() print 'GUI thread finished.' ----8<-------- The app starts up (with a warning WARNING: QApplication was not created in the main() thread. ). I get a window, but no button, and clicking on the close button does nothing and I have to force the program to quit. There's got to be a way to get this working, right? Can anyone help me along the right path? Cheers, Anders From meyer at acm.org Fri Nov 24 12:10:15 2006 From: meyer at acm.org (Andre Meyer) Date: Fri, 24 Nov 2006 18:10:15 +0100 Subject: synching with os.walk() In-Reply-To: <1164384728.336225.59840@l39g2000cwd.googlegroups.com> References: <1164384728.336225.59840@l39g2000cwd.googlegroups.com> Message-ID: <7008329d0611240910j616dc7bey733eb141d5e86e47@mail.gmail.com> Cool, this seems to work. thanks! On 24 Nov 2006 08:12:08 -0800, 120psi at gmail.com <120psi at gmail.com> wrote: > > > os.walk() is a nice generator for performing actions on all files in a > > directory and subdirectories. However, how can one use os.walk() for > walking > > through two hierarchies at once? I want to synchronise two directories > (just > > backup for now), but cannot see how I can traverse a second one. I do > this > > now with os.listdir() recursively, which works fine, but I am afraid > that > > recursion can become inefficient for large hierarchies. > > I've run into wanting to work with parallel directory structures > before, and what I generally do is something like: > > for root, dirs, files in os.walk( dir1 ): > dir2_root = dir2 + root[len(dir1):] > for f in files: > dir1_path = os.path.join( root, f ) > dir2_path = os.path.join( dir2_root, f ) > > Does this work for your needs? > -- Nils > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Dr. Andre P. Meyer http://python.openspace.nl/meyer TNO Defence, Security and Safety http://www.tno.nl/ Delft Cooperation on Intelligent Systems http://www.decis.nl/ Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams -------------- next part -------------- An HTML attachment was scrubbed... URL: From john106henry at hotmail.com Mon Nov 6 15:22:54 2006 From: john106henry at hotmail.com (John Henry) Date: 6 Nov 2006 12:22:54 -0800 Subject: adding python scripting to my application In-Reply-To: <1162794251.047389.297800@e3g2000cwe.googlegroups.com> References: <1162794251.047389.297800@e3g2000cwe.googlegroups.com> Message-ID: <1162844574.218733.142700@h48g2000cwc.googlegroups.com> Take a look at: http://www.swig.org/ Julian wrote: > Hi, first of all, I have to say I am new to Python. I have been working > with a finite element analysis program written in c++. now, I am trying > to 'rebuild' this code (possibly a full re-write) with scripting > capability. I did some reading on the web, and found that there are two > ways to do this : extending and embedding. and I still haven't figured > out what I should be using. I guess the first thing is to figure out > what I am to do with the scripting capability - at the very least, I > would like to run parametric analyses - run multiple analysis models by > changing certain parameters using for loops. > i found that the commercial fea package - abaqus uses python as well - > I don't know whether they embedded or extended ? is there any way to > find out? > another fea application called OOF2 > (http://www.ctcms.nist.gov/oof/oof2/#features) says "OOF2 is completely > scriptable in Python". and I don't really understand what that means... > maybe I haven't grasped the full potential of what python scripting > could do for an fea program. > > can you tell me how to decide what path I should take - embed or extend > ? or maybe some one could point me to some document/webpage that talks > about this. > > thanks a lot, > Julian. > > PS, my fea program uses its own script to read the analysis model > information using the c++ iostream and our own parsing functions - but > I don't have to stick to those function when I am writing the new code. From researchbase at gmail.com Thu Nov 16 09:48:18 2006 From: researchbase at gmail.com (krishnakant Mane) Date: Thu, 16 Nov 2006 20:18:18 +0530 Subject: Secure Python In-Reply-To: <1163646179.11586.60.camel@pc7.dolda2000.com> References: <1163646179.11586.60.camel@pc7.dolda2000.com> Message-ID: after reading all the mails on this thread, I have the following observations. I am relatively new to python at its development side but very old as far as using python is concerned. firstly, talking about gnu/linux there is no question about security. python, if at all it is non-secure wont harm a linux machine much any ways. secondly with OS like windows, things will be non-secure, no matter what you do. and it will be un stable and un secure no matter what language you use. how far then is python secured or non-secured in its absolute sence? I need to use python for a very mission critical project. may be I will also use zope. so I will like to know how far I can trust python for security in its absolute (platform independent ) sence? I mean running unwanted code at run-time etc. thanks. Krishnakant. From kbk at shore.net Thu Nov 30 21:55:20 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 30 Nov 2006 21:55:20 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200612010255.kB12tK59022240@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 407 open ( +1) / 3484 closed ( +5) / 3891 total ( +6) Bugs : 936 open ( +5) / 6363 closed (+14) / 7299 total (+19) RFE : 246 open ( +1) / 244 closed ( +0) / 490 total ( +1) New / Reopened Patches ______________________ sys.id() and sys.intern() (2006-11-23) http://python.org/sf/1601678 opened by Georg Brandl clarify comparison return values (2006-11-24) http://python.org/sf/1602128 opened by Jim Jewett non-framework built python fails to define environ properly (2006-11-23) http://python.org/sf/1602133 opened by paul Suggest a textlist() method for ElementTree (2006-11-24) http://python.org/sf/1602189 opened by Raymond Hettinger subprocess: error redirecting i/o from non-console process (2006-11-27) http://python.org/sf/1603907 opened by Oren Tirosh Performance boost for array repeat (2006-11-28) CLOSED http://python.org/sf/1605020 opened by Mike Klaas Make Imap Error more helpful (2006-11-29) http://python.org/sf/1605192 opened by Thomas Guettler vendor-packages directory. (2005-09-22) http://python.org/sf/1298835 reopened by loewis Patches Closed ______________ __bool__ instead of __nonzero__ (2006-11-21) http://python.org/sf/1600346 closed by jackdied SRE engine do not release the GIL (2005-11-25) http://python.org/sf/1366311 closed by eric_noyau Implement lazy read for sockets (2003-12-04) http://python.org/sf/853963 closed by loewis Disable POSIX for certain/older NetBSD versions (2003-12-05) http://python.org/sf/854796 closed by loewis Performance boost for array repeat (2006-11-28) http://python.org/sf/1605020 closed by mklaas New / Reopened Bugs ___________________ using python extension(wxPython) in c (2006-11-23) CLOSED http://python.org/sf/1601607 opened by jolleydtan getopt Documentation improvement (2006-11-23) CLOSED http://python.org/sf/1601630 opened by Thomas Guettler Incorrect docs for bisect_left (2006-11-24) http://python.org/sf/1602378 opened by Daniel Eloff itemconfigure returns incorrect text property of text items (2006-11-25) http://python.org/sf/1602742 opened by Wojciech Mula wave module forgets to close file on exception (2006-11-26) http://python.org/sf/1603150 opened by amerinese wave module forgets to close file on exception (2006-11-26) CLOSED http://python.org/sf/1603246 opened by amerinese pstats module (profiler) doens't support unicode paths (2006-11-26) CLOSED http://python.org/sf/1603321 opened by Adal Chiriliuc def foo(((x))) segfault (2006-11-26) CLOSED http://python.org/sf/1603332 opened by Tony Lownds f=open fails with TypeError (2006-11-26) CLOSED http://python.org/sf/1603336 opened by Gibholio f=open fails with TypeError (2006-11-26) CLOSED http://python.org/sf/1603412 opened by Gibholio subprocess.py (py2.5) wrongly claims py2.2 compatibility (2006-11-27) http://python.org/sf/1603424 opened by Tim Wegener Python socket library confused by IPV6 notation in /etc/host (2006-11-27) http://python.org/sf/1603527 opened by Eric S. Raymond SaveConfigParser.write() doesn't quote %-Sign (2006-11-27) http://python.org/sf/1603688 opened by Rebecca Breu grammatical error in Python Library Reference::Tkinter (2006-11-27) CLOSED http://python.org/sf/1603789 opened by Gabriel M. Elder subprocess.Popen closes fds for sys.stdout or sys.stderr (2006-11-28) http://python.org/sf/1604851 opened by Nishkar Grover _CRT_SECURE_NO_DEPRECATE macro redefinition with VC++ 8 (2006-11-28) CLOSED http://python.org/sf/1604862 opened by William Fulton logging %(module)s reporting wrong modules (2006-11-29) http://python.org/sf/1605110 opened by Mad-Marty csv module broken for unicode (2006-11-30) http://python.org/sf/1606092 opened by JettLogic readline on popen3 file returns empty string before end (2006-11-30) http://python.org/sf/1606233 opened by Bill Wallace Bugs Closed ___________ utf_8_sig decode fails with buffer input (2006-11-23) http://python.org/sf/1601501 closed by doerwalter using python extension(wxPython) in c (2006-11-23) http://python.org/sf/1601607 closed by loewis getopt Documentation improvement (2006-11-23) http://python.org/sf/1601630 closed by gbrandl ctypes Structure allows recursive definition (2006-11-17) http://python.org/sf/1598620 closed by theller 2.4 & 2.5 can't create win installer on linux (2006-10-04) http://python.org/sf/1570417 closed by loewis wave module forgets to close file on exception (2006-11-26) http://python.org/sf/1603246 closed by gbrandl pstats module (profiler) doens't support unicode paths (2006-11-26) http://python.org/sf/1603321 closed by gbrandl def foo(((x))) segfault (2006-11-26) http://python.org/sf/1603332 closed by gbrandl f=open fails with TypeError (2006-11-26) http://python.org/sf/1603336 closed by gbrandl f=open fails with TypeError (2006-11-26) http://python.org/sf/1603412 closed by nnorwitz grammatical error in Python Library Reference::Tkinter (2006-11-27) http://python.org/sf/1603789 closed by gbrandl read() in windows stops on chr(26) (2006-11-13) http://python.org/sf/1595822 closed by sf-robot _ctypes built with GCC on AIX 5.3 fails with ld ffi error (2006-09-23) http://python.org/sf/1563807 closed by theller _CRT_SECURE_NO_DEPRECATE macro redefinition with VC++ 8 (2006-11-28) http://python.org/sf/1604862 closed by loewis "make install" for Python 2.4.4 not working properly (2006-10-19) http://python.org/sf/1580563 closed by sf-robot From icetortoise at gmail.com Thu Nov 23 05:02:18 2006 From: icetortoise at gmail.com (Andy) Date: 23 Nov 2006 02:02:18 -0800 Subject: How do I find possible matches using regular expression? In-Reply-To: References: <1164272307.978986.158810@l39g2000cwd.googlegroups.com> Message-ID: <1164276138.816724.253400@l12g2000cwl.googlegroups.com> The problem is the input will be much more complex than the example, it could be something like "30 minutes later" where any string starting with a number is a possible match. Paul McGuire ??? > "Andy" wrote in message > news:1164272307.978986.158810 at l39g2000cwd.googlegroups.com... > > Hi there, > > > > I'm trying to do some predicting work over user input, here's my > > question: > > > > for pattern r'match me', the string 'no' will definitely fail to match, > > but 'ma' still has a chance if user keep on inputting characters after > > 'ma', so how do I mark 'ma' as a possible match string? > > > > Thanks a lot, > > > > Andy > > > Maybe .startsWith might be more useful than re.match, since you are > predicting user input based on characters that have been typed so far. > > -- Paul From steve at REMOVE.THIS.cybersource.com.au Mon Nov 6 22:49:17 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 07 Nov 2006 14:49:17 +1100 Subject: assigning values in __init__ References: <454faf57$0$12993$c3e8da3@news.astraweb.com> Message-ID: On Mon, 06 Nov 2006 16:57:58 -0500, John Salerno wrote: > Let's say I'm making a game and I have this base class: > > class Character(object): > > def __init__(self, name, stats): > self.name = name > self.strength = stats[0] > self.dexterity = stats[1] > self.intelligence = stats[2] > self.luck = stats[3] > > Is this a good way to assign the values to the different attributes? > Should 'stats' be a list/tuple (like this), or should I do *stats instead? Whenever possible, think about writing self-documenting code: def __init__(self, name, strength, dexterity, intelligence, luck): self.name = name self.strength = strength # etc. seems perfectly acceptable to me (if a tad verbose, but that isn't a big deal -- write once, never touch again). The problem with function signatures like these: def __init__(self, name, stats): def __init__(self, name, *stats): is that the format of stats is left unstated. Is it (luck, strength, intelligence) or (strength, intelligence, luck) or (wisdom, charisma, power, health) or something else? You shouldn't need to read the code line by line to find out, and relying on documentation risks having the code and docs get out of sync. If you expect the stats to be passed as a single tuple, you can still make it explicit: just wrap the field names within brackets. def __init__(self, name, (strength, dexterity, intelligence, luck) ): > I'm trying to think ahead to when I might want to add new attributes, If this is likely, you could do something like this: def __init__(self, name, **stats): self.name = name self.__dict__.update(stats) Adding extra attributes is fine, since they will just be ignored, but what if the caller adds an attribute "itnelligence" (instead of intelligence)? You're now writing lots of code like this: def save_intelligence(self, threshold): """Roll a saving throw against intelligence""" try: return roll(self.intelligence) > threshold except AttributeError: # character has no intelligence, so always fails return False Yes, you can make that easier with currying, decorators etc. but why not make sure your characters have the required attributes in the first place? One way of doing that would be to add default values for the required attributes in the class, and let instances inherit those defaults from the class. > and I want to make sure this doesn't get crazy with individual > parameters instead of just the one list. If you've got that many character attributes, I'm guessing that your game will be a tad hard to play :-) If you have more than a half-dozen or ten character attributes, you could consider encapsulating them in some way. E.g. group-related attributes and pass them as tuples: power => (constitution, health, anaerobic_strength, aerobic_strength) intelligence => (IQ, wisdom, dexterity, book_learning, street_wisdom) charisma => (beauty, chutzpah, attractiveness, persuasiveness) senses => (vision, hearing, smell, telepathy, empathy, feeling, spacial) others => (luck, determination, laziness, attention_to_detail) You could then roll against power, say, by giving a set of weights: character.roll('power', (0.0, 0.0, 0.9, 0.1)) gives anaerobic strength a weighting of 90% and aerobic 10%. But again, I think that if your roll-playing game needs to have such fine-grained attributes, I think it will be too complex to be fun. > Or maybe there's some way to loop through two lists (the stats and the > attributes) and assign them that way? I was thinking of a nested for > statement but that didn't seem to work. def __init__(self, stats): names = ['strength', 'dexterity', 'intelligence', 'luck'] for name, stat in zip(names, stats): setattr(self, name, stat) -- Steven. From python.list at tim.thechases.com Thu Nov 9 06:21:31 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 09 Nov 2006 05:21:31 -0600 Subject: Sorted list - how to change it In-Reply-To: References: <1163065969.593970.165600@b28g2000cwb.googlegroups.com> Message-ID: <45530F3B.3020800@tim.thechases.com> >> I have a sorted list for example [1,2,3,4,5] and I would like to change >> it in a random way >> e.g [2,5,3,1,4] or [3,4,1,5,2] or in any other way except being >> ordered. >> What is the best/easiest >> way how to do it? > > use random.shuffel: > >>>> import random >>>> x = [1,2,3,4,5] >>>> random.shuffle(x) >>>> x > [1, 4, 2, 3, 5] Just a caveat from past experience...while the OP was talking about lists, for future reference random.shuffle() chokes on strings (and possibly tuples). It requires the ability to edit the target/parameter in place...a functionality that strings don't provide. Thus, for a "word jumble" program I was playing with, you can't just do word = 'hello' random.shuffle(word) but rather you have to list'ify the word, shuffle it, then pack it back together: word = 'hello' a = list(word) random.shuffle(a) word = ''.join(a) I remember seeing discussion on the list at one point of a MutableString class, which might be successfully passed to random.shuffle() without hiccuping. -tkc From stephen.ayotte at gmail.com Mon Nov 20 09:46:24 2006 From: stephen.ayotte at gmail.com (stephen.ayotte at gmail.com) Date: 20 Nov 2006 06:46:24 -0800 Subject: os x make install dies when compiling zipfile.py on 2.5 and 2.4.4 In-Reply-To: <1162848039.627681.22980@m7g2000cwm.googlegroups.com> References: <1162848039.627681.22980@m7g2000cwm.googlegroups.com> Message-ID: <1164033984.637054.21800@h48g2000cwc.googlegroups.com> I've experienced the exact same with 2.4.4. uname -a on the machine I built it on (SunOS 5.7, binaries should be forwards-compatible with 5.7-5.10): SunOS hostname-here 5.7 Generic_106541-19 sun4u sparc SUNW,Ultra-4 And the machine on which it was being installed (because it has write access to the NFS mount I want it installed on): SunOS hostname-here 5.10 Generic_118822-25 sun4u sparc SUNW,Sun-Fire-V210 I only *just* hit this and haven't dug further for a solution. If anyone knows about this please respond, otherwise I'll post any progress I make. On Nov 6, 4:20 pm, "metaperl" wrote: > I've tried both Python 2.4.4 and Python 2.5. I'm trying to build from > source and install under a local directory Swarm since OpenSwarm > requires builds of Postgres and Python under it's control. > > Ok, so I did > > ./configure --prefix=/Users/tbrannon/Documents/Python/Swarm/Python-2.5 > > but during make install I get this: > > Compiling > /Users/tbrannon/Documents/Python/Swarm/Python-2.5/lib/python2.5/xmlrpclib.py > ... > Compiling > /Users/tbrannon/Documents/Python/Swarm/Python-2.5/lib/python2.5/zipfile.py > ... > make: *** [libinstall] Error 1 > > > and the same thing happens for Python 2.4.4 leaving me without a > platform-depedent install directory in my build.. any ideas? From robert.kern at gmail.com Thu Nov 2 13:02:34 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 02 Nov 2006 10:02:34 -0800 Subject: Python in sci/tech applications In-Reply-To: <1162489638.013433.102180@h48g2000cwc.googlegroups.com> References: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> <1162489638.013433.102180@h48g2000cwc.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > mattf: >> 3) -There's a problem with development under Windows. > > It's possibile to compile Python with MinGW, and to create extensions > with it. So some site can host a single zip file that contains both > MinGW and Python compiled with it, all ready and set. A person not much > expert can then create compiled small extensions in a short time > without too much complexities. (Or maybe the D language can be packed > into that, instead of MinGW, to do similar things. D can be a good > language used with Python) But then probably PIL, scipy, etc have to be > compiled again for such alternative official or semi-official Python > distribution. With a few caveats, mingw will simply work with the standard 2.4 (and presumably 2.5) interpreter. We distribute mingw set up to do this with our "Enthought Edition" Python distribution. http://code.enthought.com/enthon/ -- 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 horpner at yahoo.com Thu Nov 9 08:37:40 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 9 Nov 2006 14:37:40 +0100 Subject: Problem getting a file pathname with tkFileDialog References: <1163012468.055428.124690@h48g2000cwc.googlegroups.com> <1163016063.961485.224390@k70g2000cwa.googlegroups.com> <1163060986.314142.22060@k70g2000cwa.googlegroups.com> Message-ID: On 2006-11-09, jmdeschamps at gmail.com wrote: > you could also use encode("iso-8859-1") to nterpret just the > printed name such as: print myfilename.encode("iso-8859-1") > > and by the way if you wanted the file NAME you could have used > openfilename() instead of openfile() ;-) The encoding of the filenames in the file system is available from sys.getfilesystemencoding(). That might turn out to be useful when interpreting them. -- Neil Cerutti Strangely, in slow motion replay, the ball seemed to hang in the air for even longer. --David Acfield From robert.kern at gmail.com Tue Nov 7 18:40:59 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 07 Nov 2006 17:40:59 -0600 Subject: Finding Nonzero Elements in a Sparse Matrix In-Reply-To: <1162937813.360645.3040@h54g2000cwb.googlegroups.com> References: <1162937813.360645.3040@h54g2000cwb.googlegroups.com> Message-ID: deLenn wrote: > Hi, > > Does scipy have an equivalent to Matlab's 'find' function, to list the > indices of all nonzero elements in a sparse matrix? You will want to ask scipy questions on the scipy list. http://www.scipy.org/Mailing_Lists There is no explicit interface on sparse matrix objects to expose the indices of the nonzero elements. A different implementation would have to be written for each type of sparse matrix format. However, if one can spare the memory, one can convert to the coordinate list format and read the row and column indices from that object. In [1]: from scipy.sparse import lil_matrix In [2]: A = lil_matrix((3,3)) In [3]: A[1,2] = 10 In [4]: A[2,0] = -10 In [5]: Acoo = A.tocoo() In [6]: Acoo.row Out[6]: array([2, 1]) In [7]: Acoo.col Out[7]: array([0, 2]) -- 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 Roberto.Bonvallet at cern.ch Tue Nov 14 10:06:27 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Tue, 14 Nov 2006 15:06:27 +0000 (UTC) Subject: sqlite3 views, if not exists clause References: <4559c572$0$560$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Fredrik Lundh wrote: > "Josh" wrote: > >> THIS DOES NOT WORK, but it should! > > Python 2.5 was released on September 19th, 2006, and support for CREATE > VIEW IF NOT EXISTS was added to sqlite on October 9th, 2006: So? "from __future__ import ..." should have supported this! <:o) -- Roberto Bonvallet From spe.stani.be at gmail.com Wed Nov 29 18:03:13 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 29 Nov 2006 15:03:13 -0800 Subject: Good script editor for Python on Mac OS 10.3 In-Reply-To: <1164830360.213197.182560@l12g2000cwl.googlegroups.com> References: <1164830360.213197.182560@l12g2000cwl.googlegroups.com> Message-ID: <1164841393.939122.202630@80g2000cwy.googlegroups.com> Install wxPython and than you can use SPE, a free Python IDE with UML, GUI builders, ... Stani Scott_Davies wrote: > Hi, > > I have an old Mac with OS X Panther installed. I also have the Python > language download file, but I haven't got a text/script editor to use > for it. Does anyone have a recommendation for a good Python text > editor in OS 10.3? > > Thanks, > > Scott D. From pavlovevidence at gmail.com Mon Nov 13 20:16:39 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 13 Nov 2006 17:16:39 -0800 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <17750.22816.636590.485360@montanaro.dyndns.org> <4558B9E3.2040207@hobbshouse.org> Message-ID: <1163466999.563860.30680@m73g2000cwd.googlegroups.com> Ben Finney wrote: > Michael Hobbs writes: > > > To be clear, this is the actual thrust of my argument. It seems > > redundant to have *both* line continuations and colons in compound > > statements. > > Why are you trying to remove redundancy? The language is designed for > communication between people (programmers) primarily. Redundancy is > often the best way to be explicit and readable. Well, Python *is* quite a notorious redundancy minimizer.... Carl Banks From nicolasg at gmail.com Wed Nov 8 17:23:09 2006 From: nicolasg at gmail.com (NicolasG) Date: 8 Nov 2006 14:23:09 -0800 Subject: help using smtplib to work .. Message-ID: <1163024588.884055.12460@i42g2000cwa.googlegroups.com> I'm using the following code to send e-mail through python: import smtplib fromaddr = 'myMail at gmail.com' toaddrs = 'myOtherMail at gmail.com' subject = 'someting for subject !' msg = 'This is body of the mail.' msg = 'From: ' + fromaddr + '\nTo: ' + toaddrs + '\nSubject:' + subject + '\n\n' + msg print "Message length is " + repr(len(msg)) server = smtplib.SMTP('smtp.gmail.com') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() I have replaced the sender and receiver's mail address with the original ones but executing this code I get the error (ip is hided for obvious reason): send: 'ehlo computer.domain_not_set.invalid\r\n' reply: '250-mx.google.com at your service, [xxx.xx.xxx.xxx]\r\n' reply: '250-SIZE 20971520\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250 ENHANCEDSTATUSCODES\r\n' reply: retcode (250); Msg: mx.google.com at your service, [xxx.xx.xxx.xxx] SIZE 20971520 8BITMIME STARTTLS ENHANCEDSTATUSCODES send: 'mail FROM: size=106\r\n' reply: '530 5.7.0 Must issue a STARTTLS command first s1sm7666914uge\r\n' reply: retcode (530); Msg: 5.7.0 Must issue a STARTTLS command first s1sm7666914uge send: 'rset\r\n' reply: '250 2.1.0 Flushed s1sm7666914uge\r\n' reply: retcode (250); Msg: 2.1.0 Flushed s1sm7666914uge Traceback (most recent call last): File "C:\Documents and Settings\NicolasG\Desktop\smtpexample.py", line 17, in server.sendmail(fromaddr, toaddrs, msg) File "C:\Python25\lib\smtplib.py", line 684, in sendmail raise SMTPSenderRefused(code, resp, from_addr) SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first s1sm7666914uge', 'myMail at gmail.com') What am I doing wrong ? From dlenski at gmail.com Thu Nov 9 15:12:31 2006 From: dlenski at gmail.com (Dan Lenski) Date: 9 Nov 2006 12:12:31 -0800 Subject: How to choose the right GUI toolkit ? In-Reply-To: <1163102807.741768.195310@m73g2000cwd.googlegroups.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163092380.301382.113470@m7g2000cwm.googlegroups.com> <1163102807.741768.195310@m73g2000cwd.googlegroups.com> Message-ID: <1163103151.772022.300950@k70g2000cwa.googlegroups.com> John Henry wrote: > I assume you meant that the example programs looks LabView-like GUIs? > PythonCard itself has nothing in common with LabView. It's more like > HyperCard. That's right, I'm saying the GUIs *produced* by PythonCard look like those produced by LabView. Believe me, if the PythonCard programming style had anything to do with LabView, I'd avoid it like the plague =) In any case, I think I'm gonna give PythonCard a shot before trying full-fledged wxPython. It looks ideal for my needs. Dan From cyberco at gmail.com Mon Nov 20 06:17:51 2006 From: cyberco at gmail.com (cyberco) Date: 20 Nov 2006 03:17:51 -0800 Subject: mod_python + fileinput => permission denied Message-ID: <1164021471.620435.14450@k70g2000cwa.googlegroups.com> Opening, reading and writing to a file works fine in mod_python, but using fileinput (with inplace editing) gives me a 'permission denied' with exactly the same fileName: ========================= fileinput.input(fileName, inplace=1) ========================= I suspect that this has to do with the temporary file it creates, or am I wrong? From antroy at gmail.com Thu Nov 9 10:03:09 2006 From: antroy at gmail.com (Ant) Date: 9 Nov 2006 07:03:09 -0800 Subject: Can not download plugins for jEdit (help!!) In-Reply-To: References: <1163055167.418011.236870@h48g2000cwc.googlegroups.com> <1163066294.697993.148680@h48g2000cwc.googlegroups.com> <1163078175.600579.22930@h54g2000cwb.googlegroups.com> Message-ID: <1163084589.148065.212640@h48g2000cwc.googlegroups.com> On Nov 9, 2:11 pm, Neil Cerutti wrote: ... > """ never are. Then I changed the synchronize declarations in > /syntax/python.vim to the following: > > syn sync match pythonSync grouphere NONE '"""$' > syn sync maxlines=300 > > The above is no good for random Python code, though. > > But in random Python code you can simply increase the number of > lines inspected as high as your machine can handle, as documented > in python.vim. I commented out the maxlines line, and uncommented the syn sync minlines=2000 line, and that seems to have worked. > The reason I haven't adapted quickfix mode to Python is that Vim > would hide most of the Traceback. I'd constantly be executing the > command to show the entire error message, so I've chosen to > eschew quickfix mode for Python code. Sounds interesting - I may take a look at it. > ... default Python plugin provides the [[, ]] and [m, ]m commands > for jumping to the next function or method respectively. They are > a nice help once you're aware of them. There's a more powerful > plugin available on the internet, but it the code-jumps were the > main commands I wanted. They sound good. I've been using the taglist.vim plugin for code browsing which is pretty good for that sort of thing. > pytags should be in your Tools directory. I haven't found it > terribly useful, but in theory it's invaluable (my project is > piddly in size at the moment). I'll take a look. A code navigation tool I presume? > If you set shiftwidth to your preferred Python indent, then > indenting and unindenting code blocks is as easy as the < and > > commands Yes - I have that set up. Thanks for the tips :-) From rtw at freenet.co.uk Sat Nov 11 13:20:20 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 11 Nov 2006 12:20:20 -0600 Subject: odd problem with watsup and VB6 application with modal dialog References: Message-ID: Grumman wrote in news:JNc5h.194$3i6.48 at newsfe03.lga in comp.lang.python: [snip] > Roughly, I have a script that fills in a field, sets a combobox, then > clicks a button via clickButton. At this point, the python interpreter > hangs. The only thing I've been able to identify as different about > this form is that it is set as dialog-modal. > > I've managed to work around this by adding a second python script that > contains just enough code to click the offending button. I call it via > os.system('start other.py') and it starts in a different process, > clicks the button then hangs. > > But the main script continues on to fill in the following form, and > click another button. When the VB app returns to its starting form, > destroying the other form instances, the hung interpreter ends. > > This works, but it is quite the ugly kludge isn't it? > > Is this a normal behaviour for watsup with modal windows? Is there a > saner way around it? AFAICT the problem is that the clickButton() function calls the internal windows API function SendMessage(), which waits for the buttons event handler to return something. There is an alternative PostMessage(), which returns as soon as the message is put in the target windows message queue. A potential proplen with this is that it will return immediately so the caller will need to wait (time.sleep) until the button handler has recieved the message and done something about it. Here's a rewrite of the winGuiAuto.clickButton function, post_clickButton() that uses PostMessage: def post_clickButton( hwnd ): '''All code here adapted from winGuiAuto.py see http://www.tizmoi.net/watsup/intro.html ''' def _buildWinLong(high, low): '''Build a windows long parameter from high and low words. See http://support.microsoft.com/support/kb/articles/q189/1/70.asp ''' return int( 0xFFFFFFFF & ( (high << 16) | (low & 0xFFFF) ) ) def _postNotifyMessage(hwnd, notifyMessage): '''Post a notify message to a control.''' import win32gui import win32con import win32api win32gui.PostMessage( win32gui.GetParent(hwnd), win32con.WM_COMMAND, _buildWinLong( notifyMessage, win32api.GetWindowLong(hwnd, win32con.GWL_ID) ), hwnd ) import win32con _postNotifyMessage( hwnd, win32con.STN_CLICKED ) if __name__=='__main__': '''Just here to show how it works, this code won't actually work unless you have a sutible GUI programme running. ''' from watsup.winGuiAuto import \ findControl,setEditText, \ findTopWindow,clickButton from time import sleep def main(): form=findTopWindow(wantedText='Main_Form') button=findControl(form,wantedText='Open') print 'clicking button to open dialog...' post_clickButton(button) sleep( 0.5 ) form=findTopWindow(wantedText='Dialog_Form') button=findControl(form,wantedText='Close') print "clicking close button" post_clickButton(button) main() Rob. -- http://www.victim-prime.dsl.pipex.com/ From harry.g.george at boeing.com Wed Nov 29 09:34:23 2006 From: harry.g.george at boeing.com (Harry George) Date: Wed, 29 Nov 2006 14:34:23 GMT Subject: Pimping the 'cgi' module (was: Re: python gaining popularity according to a study) References: <1164306918.845529.95820@f16g2000cwb.googlegroups.com> Message-ID: Christoph Haas writes: > On Thursday 23 November 2006 21:29, robert wrote: > > When a LAMP programmer comes to Python, there are so many different > > confusing things. It starts with a 'non-documented' cgi module - a > > 'High-Level-Interface', that cannot even iterate over the form items. A > > name ZOPE in focus which reveals to be a monster system with 2-year > > learning-curve, ready for running an article editorial system for TOP-10 > > newspaper companies, but unable to make simple things simple. A handful > > of different Djangos - choose one for each weekday and programmer ... > > And Ruby made it with this single-known simple URL-to-method-router (And > > possibly when coming from PHP & Perl one recognizes ::@$_$%??%/&... and > > the old namespace dirt) If there would have been a good cgi-system and a > > somewhat comfortable advanced URL-to-OO-router (beyond the socket > > wrapper HTTPServer) well exposed in the Python standard lib, the numbers > > would be probably very different today ... > > I can fully second that. Coming from Perl and being used to the CGI module > that is de-facto standard and already doing things much better than > Python's equivalent my first thought was: "Does Python really expect me to > re-invent the wheel to write basic CGIs?" So I started creating > cookie-based session handlers, form field handling etc. > > The reason of my posting it not only to complain though. My Python skills > are average but I would really like to help contribute some code on this > topic. I don't know Ruby-on-Rails myself but I have worked with CGIs for > ten years both in C (yuk) and Perl (Perl=semi-yuk / Perl-CGI=yum) and > think I know what people coming from Perl expect. And I'm not speaking of > Zope or Django or huge frameworks. I try to avoid frameworks wherever I > can (I want to write Python - not Zope or Django). I rather rely on the > standard library unless it's really saving me time and worth learning > another language. Are frameworks perhaps even telling that the standard > library is still lacking in some way? > > I'm thinking of features like: > - cookie handling > - cookie-session handling (similar to PHP or Perl's CGI::Session; combined > with database backends or simple text files) > - handling of form fields (Perl's CGI class can easily redisplay what > has been entered in the fields when they got submitted through a
) > - accessing parameters (honestly I haven't yet understood why I need to use > .value on FielStorage dictionaries - why isn't it just a plain > dictionary?) > - state keeping (storing the contents of all form fields on disk > to retrieve it later) > - creating form elements easily (option lists for example from > dictionaries and lists like in Perl) > - creating standard HTML elements (or do you remember how DOCTYPE > looks without looking it up?) > - handling of file uploads (which is just a recipe on ActivePython > at the moment) > - controlling HTTP headers (expires, redirections, charset) > - convenience functions e.g. for getting the client IP address without > needing to read ENV['REMOTE_ADDR'] > > Well, of course there are modules like 'cgi' or 'cookielib' and others may > argue that everything is already there. And there is a 'Web.py' already (I > assume every CGI programmer has written their own Web.py already). But > can't we come closer to what other scripting languages provide? Something > common? Can't a simple form-based CGI just be a matter of a dozen lines? > When it comes to CGIs Python loses its elegance for no reason. > > I'm ready to invest work and ideas if anyone else is interested. Perhaps > some day it makes it into the standard library or at least gives us > something between the features of the standard library and huge framework > monsters - something people can be pointed at when starting with Python > and CGIs. I'll probably do that anyway because my web projects all use > their own reinvented wheel and I'm losing the overview. And even Perl has > come that route - it started with a cgi-lib.pl which later became > the 'CGI' standard module. > > Is it just a matter of lacking resources or interest? Even if there is no > interest I'll probably read "man CGI" and "man CGI::Session" again and > start implementing something nifty for ex-perlies like myself. Hmmm, > batteries included even for CGI programmers, a man can dream. :) > > Cheers > Christoph When I came from Perl, I too missed perl-isms and specifically CGI.pm, so wrote my own: http://www.seanet.com/~hgg9140/comp/index.html http://www.seanet.com/~hgg9140/comp/pyperlish/doc/manual.html http://www.seanet.com/~hgg9140/comp/cgipm/doc/index.html Others on this newsgroup said I'd be better off just doing it in raw python. After a while, I realized that was true. You do triple-quoted templates with normal python idioms. Throw in some persistence mechanisms to deal with maintaining state across transactions, and you are in business. Since then I've looked at Zope, Plone, TurboGears, Django, and (for standalone apps) Dabo. TurboGears is mostly a set of recommendations on what 3rd party packages to use, with a wee bit of glueware. So far nothing feels as simple as just doing it in python. -- Harry George PLM Engineering Architecture From timothy at open-networks.net Thu Nov 9 17:34:42 2006 From: timothy at open-networks.net (timmy) Date: Fri, 10 Nov 2006 08:34:42 +1000 Subject: SPE bug? Message-ID: <4553ac8a@quokka.wn.com.au> i can't paste from SPE into an xterm window. is this problem with SPE? From john at castleamber.com Sat Nov 18 16:21:15 2006 From: john at castleamber.com (John Bokma) Date: 18 Nov 2006 21:21:15 GMT Subject: MAKE GOOD MONEY BY INTERNET References: <1163848933.731124.307470@e3g2000cwe.googlegroups.com> Message-ID: "Paul McGuire" wrote: > Congratulations, dumbfuck -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From john at castleamber.com Sat Nov 18 01:25:43 2006 From: john at castleamber.com (John Bokma) Date: 18 Nov 2006 06:25:43 GMT Subject: decompiler References: <1163822905.706713.216940@e3g2000cwe.googlegroups.com> Message-ID: "jim" wrote: > Is there such thing as a free decompile that I can run in windows xp You asked the same Q in comp.lang.perl.misc... -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From prouleau001 at gmail.com Thu Nov 16 11:58:42 2006 From: prouleau001 at gmail.com (prouleau001 at gmail.com) Date: 16 Nov 2006 08:58:42 -0800 Subject: atexit.register does not return the registered function. IMHO, it should. In-Reply-To: References: <1163693028.543926.163320@f16g2000cwb.googlegroups.com> Message-ID: <1163696322.614398.23650@h54g2000cwb.googlegroups.com> On Nov 16, 11:38 am, Carsten Haese wrote: > On Thu, 2006-11-16 at 08:03 -0800, prouleau... at gmail.com wrote: > > @atexit.register > > def goodbye(): > > print "Goodbye, terminating..." > > > However, there is one fundamental problem with this: atexit.register() > > returns None. Since the above code corresponds to:: > > > def goodbye(): > > print "Goodbye, terminating..." > > goodbye = atexit.register(goodbye) > > > the code registers goodbye but right after it binds goodbye to None!While it wouldn't hurt to have atexit.register return the function it > registered, this "problem" is only a problem if you wish to call the > function manually, since atexit already registered the reference to the > intended function before your reference to it gets rebound to None. > Normally one would register a function with atexit precisely because > they don't want to call it manually. > There are *two* problems. 1 - As you said, most of the time you would not call the function explicitly, but in some situation you might want to. 2- If you want to document your code using introspection, or use an IDE to look at the function, if the function disappeared from sight, you won't be able to. The second problem is similar to what happens when a decorator changes the signature of a function. -- P.R. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Nov 23 17:35:58 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 23 Nov 2006 23:35:58 +0100 Subject: Access to variable from external imported module References: <1164316786.875306.276460@h54g2000cwb.googlegroups.com> <1164319761.451409.196660@j44g2000cwa.googlegroups.com> Message-ID: <4smm2eF10389oU1@mid.individual.net> GinTon wrote: > Sorry, I mean access to local variable from a method > > import module > method(value) That's no access to a local variable of a method. It's a simple function call. > I would to access to values that are created locally in that > method Something with your interface seems horribly wrong. Regards, Bj?rn -- BOFH excuse #316: Elves on strike. (Why do they call EMAG Elf Magic) From prabhusanthanam at yahoo.com Tue Nov 7 08:28:04 2006 From: prabhusanthanam at yahoo.com (prabhusanthanam) Date: Tue, 07 Nov 2006 13:28:04 -0000 Subject: Python, PHP Developers required for a company in Bangalore. Message-ID: Python, PHP Developers required for a company in Bangalore. Hi, We have immediate requirements for Python, PHP Developers with our client in Bangalore. Skillset : Linux/ Solaris/ FreeBSD/ etc. Apache HTTP Server, MySQL Database , PHP , Ruby , Ruby on Rails Web Framework, Python Programming Language , Tcl / Expect Programming Language Experience : 5+ years. Education : BE/Btech/ME/M.Tech/MCA. Job Type : Permanent Job Location : Bangalore. If interested in this opportunity kindly email your updated CV with contact numbers to andre_unix@ yahoo.com Do mention in the subject line "Resume for Python, PHP Developers requirement in Bangalore." Request you to kindly provide the following details required by the client while applying: Experience: Current CTC : Expected CTC: Lead time to Join: Current Company and Location: thank you, Ganesh C From wo_shi_big_stomach at mac.com Fri Nov 24 22:14:58 2006 From: wo_shi_big_stomach at mac.com (wo_shi_big_stomach) Date: Fri, 24 Nov 2006 19:14:58 -0800 Subject: combining the path and fileinput modules In-Reply-To: <7.0.1.0.0.20061124234209.03442fe0@yahoo.com.ar> References: <1164291336.523872.131610@h54g2000cwb.googlegroups.com> <4565BC89.9060901@mac.com> <7.0.1.0.0.20061124234209.03442fe0@yahoo.com.ar> Message-ID: <4567B532.4030906@mac.com> Gabriel Genellina wrote: > The filter should be applied to walkfiles. Something like this: > > dir = path(/home/wsbs/Maildir) > for f in filter(os.path.isfile, dir.walkfiles('*')): > # > # test: > # print f Thanks, this way f will print the full pathname/filename. But f already does that using Jason Orendorff's path module: dir = path('/home/wsbs/Maildir') for f in dir.walkfiles('*'): print f Printing the full path/filename isn't the problem. The problem instead is how to supply f to fileinput.input(). Either the path or the os.path methods cause this line: for line in fileinput.input(f, inplace=1, backup='.bak'): to throw this error: File "./p2.py", line 23, in ? for line in fileinput.input(f, inplace=1, backup='.bak'): At this point I believe the error has to do with fileinput, not the path or os.path modules. If I give fileinput.input() a hardcoded path/filename in place of 'f' the program runs. However the program will not accept either f or 'f' as an argument to fileinput.input(). Again, thanks for guidance on the care and feeding of fileinput.input() /wsbs import fileinput import os import re import string import sys from path import path # p.pl - fix broken SMTP headers in email files # # recurses from dir and searches all subdirs # for each file, evaluates whether 1st line starts with "From " # for each match, program deletes line # recurse dirs dir = path('/home/wsbs/Maildir') #for f in dir.walkfiles('*'): for f in filter(os.path.isfile, dir.walkfiles('*')): # # test: this will print the full path/filename of each file print f # # open file, search, change if necessary, write backup # for line in fileinput.input('f', inplace=1, backup='.bak'): # # just print 2nd and subsequent lines # if not fileinput.isfirstline(): # print line.rstrip('\n') # # check first line only # elif fileinput.isfirstline(): # if not re.search('^From ',line): # print line.rstrip('\n') # fileinput.close() From horpner at yahoo.com Wed Nov 29 10:46:32 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 29 Nov 2006 16:46:32 +0100 Subject: trouble writing results to files References: <1164812827.653386.323320@80g2000cwy.googlegroups.com> Message-ID: On 2006-11-29, Roberto Bonvallet wrote: > Neil Cerutti wrote: >> On 2006-11-29, Roberto Bonvallet wrote: >>> BTW, iterating over range(len(a)) is an anti-pattern in Python. >> >> Unless you're modifying elements of a, surely? > > enumerate is your friend :) > > for n, item in enumerate(a): > if f(item): > a[n] = whatever I was going to bring it up but I had a brainfart about the order of (n, item) in the tuple and was too lazy to look it up. ;-) -- Neil Cerutti From chrisBrat at gmail.com Tue Nov 21 03:46:21 2006 From: chrisBrat at gmail.com (Chris Brat) Date: 21 Nov 2006 00:46:21 -0800 Subject: class method vs static method Message-ID: <1164098781.577358.90850@j44g2000cwa.googlegroups.com> Hi, I've done some reading up but I cant get my head around how/why class methods can be used as apposed to static methods. Can anyone give an example of where they have used class methods? Thanks, Chris From mgiann at beta-cae.gr Mon Nov 27 05:15:18 2006 From: mgiann at beta-cae.gr (Michalis Giannakidis) Date: Mon, 27 Nov 2006 12:15:18 +0200 Subject: Inheritance from builtin list and override of methods. In-Reply-To: References: <200611261804.54669.mgiann@beta-cae.gr> <200611271133.48359.mgiann@beta-cae.gr> Message-ID: <200611271215.18792.mgiann@beta-cae.gr> On Monday 27 November 2006 11:50, Fredrik Lundh wrote: > "obj[index] = value" maps to "obj.__setitem__(index, value)". reading > the documentation might help; start here: > > http://docs.python.org/ref/specialnames.html In this documentation page it also says: --snip--- then x[i] is equivalent3.2 to x.__getitem__(i). --snip-- This, and other statements, are only roughly true for instances of new-style classes. --snip-- So which statements are actually true for new style classes? Is l[0]=1 completely different from l.append(1) or maybe insert? And is there a mechanism in Python that will allow me to override the operators of a class, for all its occurrences, even the ones implemented on C built-in objects? -- Michalis Giannakidis From bignose+hates-spam at benfinney.id.au Thu Nov 9 18:56:04 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 10 Nov 2006 10:56:04 +1100 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> Message-ID: <87ac30kwdn.fsf@benfinney.id.au> Please don't hide your new thread as a reply to an existing, unrelated message. Start a new message if your message isn't actually a reply. Michael Hobbs writes: > Can anyone find a flaw with this change in syntax? > > Instead of dividing a compound statement with a colon, why not > divide it on a newline? For example, the colon could be dropped from > this statement: > if self.hungry: > self.eat() > to > if self.hungry > self.eat() But it can't be dropped from this statement: if self.hungry: self.eat() > The colon that divides the statement therefore seems redundant. The > colon could continue to be used for single-line statements: > if self.hungry: self.eat() Why have two different syntaxes for the same statement? > I think the colon could be omitted from every type of compound > statement: 'if', 'for', 'def', 'class', whatever. Am I missing > anything? A use case. What problem is being solved by introducing this inconsistency? -- \ "The shortest distance between two points is under | `\ construction." -- Noelie Alito | _o__) | Ben Finney From paul at boddie.org.uk Thu Nov 16 15:16:50 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Nov 2006 12:16:50 -0800 Subject: Python v PHP: fair comparison? References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> <1163681949.338244.323390@k70g2000cwa.googlegroups.com> <1163697632.352189.110920@h54g2000cwb.googlegroups.com> Message-ID: <1163708210.203188.230260@f16g2000cwb.googlegroups.com> John Bokma wrote: > "Luis M. Gonz?lez" wrote: > > > > I know, but would you consider a python cgi application a good > > competence against php? > > php running as cgi you mean. Perhaps not: he's referring to deployment on really cheap hosting solutions which might support mod_php but wouldn't support anything better than CGI for Python software. The suitability of mod_php and the supposed unsuitability of mod_python for commodity hosting did come up on comp.lang.python some time ago, a while before certain other trends, and has seemingly been discussed every year for several years: http://groups.google.co.uk/group/comp.lang.python/msg/ebf390af4ed6e92e "Thus, for mod_python hosting to be reliable, you have to give each user their own instance of the Apache server (proxied through a central instance of Apache). This might, in fact, no longer be needed with the latest mod_python, but I leave that to the mod_python experts in this newsgroup to expound upon if so." (To which there was no response.) This discussion only differs from those previous discussions [1] in the sense that better hosting is now available for less, although you can't get a virtual server for $1/month unless you have some contacts in the business. Paul [1] http://groups.google.co.uk/groups?oi=djq&as_q=mod_python+PHP+hosting From fredrik at pythonware.com Wed Nov 29 11:00:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Nov 2006 17:00:30 +0100 Subject: trouble writing results to files In-Reply-To: References: <1164812827.653386.323320@80g2000cwy.googlegroups.com> Message-ID: Neil Cerutti wrote: >> BTW, iterating over range(len(a)) is an anti-pattern in Python. > > Unless you're modifying elements of a, surely? and needs to run on a Python version that doesn't support enumerate. From fredrik at pythonware.com Wed Nov 15 06:48:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Nov 2006 12:48:27 +0100 Subject: Decimal() instead of float? In-Reply-To: <4559F828.7070704@holdenweb.com> References: <1163294604.4675.4.camel@pepper> <1163511997.4675.88.camel@pepper> <4559F828.7070704@holdenweb.com> Message-ID: Steve Holden wrote: >> It /would/ be nice to see Decimal() become the default. I cannot >> imagine why in an otherwise "human enough" language, math wouldn't be >> included in that without going out of one's way to do it. :-) >> > Speed has a lot to do with it. Have you timed some decimal operations > against their floating-point counterparts? It might be possible to build > a version of Python that used decimal instead of floating-point but it > certainly wouldn't be trivial: consider the use of C language libraries > that know nothing of Python's decimal representation. judging from the various decimal FAQ:s, I think it's a bit naive to think that using Decimal instead of float would somehow make everything "just work": http://www2.hursley.ibm.com/decimal/decifaq.html http://effbot.org/pylib/decimal.htm#decimal-faq (btw, the OP mentioned in private mail that he wanted to store geographical coordinates in decimal because floats kept messing things up, but given that a 64-bit float can hold enough decimal digits to represent a geographical coordinate with sub-millimeter precision on a global scale, I'm not sure I buy that argument. I suspect he was just tricked by the usual repr(1.15) != "1.15" issue. and seriously, under- standing the various aspects of floats and decimals is utterly trivial compared to all the nearly-magical things you need to understand to be able to do geographical calculations at a sub-millimeter scale. heck, even sub-kilometer stuff is pretty hard to get right ;-) From ludwig.frank at gmail.com Fri Nov 24 20:29:34 2006 From: ludwig.frank at gmail.com (ludwig.frank at gmail.com) Date: 24 Nov 2006 17:29:34 -0800 Subject: mouse clicks in console window delayed Message-ID: <1164418174.204455.32940@m7g2000cwm.googlegroups.com> Hi, I am attempting to detect mouse clicks from within curses, using "select" on sys.stdin. It is working great within an xterm under X, but not very well in a "real" linux console. When I click my mouse while on the "real" console, nothing happens at first, even on repeated clicks. Once I press a keyboard key, I see a "409" in my trace, indicating the mouse event. The next keystroke will bring up the two keyboard events. The additional mouse clicks (all but the first or all but the last, I don't know) are lost. I am wondering if someone could tell me why this is happening, and more importantly, what to do about it (short of changing the entire detection loop to busy polling. I noticed I am not the first with this problem but I haven't yet found a solution posted. Additional observations: Happens with the last gpm, regardless whether compiled --without-curses or not. I do see my mouse events happen instantly watching the output of gpm's "mev". Interestingly, I see the mouse clicks almost immediately when I code a busy loop around screen.getch(). System info: Python 2.5, OpenSuse 10.1, gpm 1.20.1, tried several terminal types without seeing a difference. Thanks in advance, Frank From sjmachin at lexicon.net Thu Nov 9 02:44:04 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Nov 2006 23:44:04 -0800 Subject: opening excel In-Reply-To: <4552d34b$1@quokka.wn.com.au> References: <4552d34b$1@quokka.wn.com.au> Message-ID: <1163058244.735201.62830@h48g2000cwc.googlegroups.com> timmy wrote: > Hello, > > has anybody got any experience opening and manilpulating excel > spreedsheets via python? it seems pythoncom allows this to happen but > i'm a total newb to it. (i usually work in the unix world) > all i need to do, is open the xls files and read values from it. If you really mean "read" rather than "manipulate", have a look at the xlrd package (of which I'm the author). http://www.python.org/pypi/xlrd BTW, it's pure Python; you can run it on your unix box if you like :-) Cheers, John From grante at visi.com Wed Nov 29 12:32:37 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Nov 2006 17:32:37 -0000 Subject: pickle and infinity References: <1164820161.480995.180500@l12g2000cwl.googlegroups.com> Message-ID: <12mrh1lgbaomca1@corp.supernews.com> On 2006-11-29, Bart Ogryczak wrote: > I?ve got this problem with pickle, it seems it doesn?t handle > correctly infinite values (nor does Python return > overflow/underflow error). What could I do about it? Here's what I did. I'm sure it'll fall down on some systems, but it works on Linux and Windows. ______________________________________________________________________ # unpickle can't handle nan/inf/ind floats, so we need to # handle that ourselves def myload_float(self): s = self.readline()[:-1] try: f = float(s) except ValueError: s = s.upper() if s in ["1.#INF", "INF"]: f = 1e300*1e300 elif s in ["-1.#INF", "-INF"]: f = -1e300*1e300 elif s in ["NAN","1.#QNAN","-1.#QNAN","QNAN","1.#IND","IND","-1.#IND"]: f = (1e300*1e300)/(1e300*1e300) else: raise ValueError, "Don't know what to do with "+`s` self.append(f) # unpickle routine that overrides the float load method def unpickle(f): unpickler = pickle.Unpickler(f) unpickler.dispatch[pickle.FLOAT] = myload_float return unpickler.load() ______________________________________________________________________ -- Grant Edwards grante Yow! I represent a at sardine!! visi.com From claird at lairds.us Sat Nov 25 18:58:00 2006 From: claird at lairds.us (Cameron Laird) Date: Sat, 25 Nov 2006 23:58:00 +0000 Subject: Dynamic function execution References: <1164469406.980376.194150@h54g2000cwb.googlegroups.com> Message-ID: <8t1n34-qsv.ln1@lairds.us> In article , Fredrik Lundh wrote: >Andy Wu wrote: > >> def func(seconds = None, minutes = None, hours = None): >> ... >> >> In my program I can get a string object('seconds', 'minutes', 'hours') >> to specify which parameter to use, the problem is I don't know how to >> call the function. >> >> Say I have a string 'minutes' and a integer 30, now I need to call the >> func this way: func(minutes = 30), how do I do this? > > func(**{"minutes": 30}) > > > Now I'm confused: what's the advantage of def func(seconds = None, minutes = None, hours = None): print seconds print minutes print hours func(**{"minutes": 30}) over def func(seconds = None, minutes = None, hours = None): print seconds print minutes print hours func(minutes = 30) ? Or am I missing the point that a better example of what Mr. Wu really wants is def func(seconds = None, minutes = None, hours = None): print seconds print minutes print hours dimension = "minutes" func(**{dimension: 30}) ? From walterbyrd at iname.com Thu Nov 16 18:15:48 2006 From: walterbyrd at iname.com (walterbyrd) Date: 16 Nov 2006 15:15:48 -0800 Subject: Python v PHP: fair comparison? In-Reply-To: References: <136ED738BD4F1545B97E4AC06FF6370734BFDC@DMSP-MSG-EVS01.mail.pvt> Message-ID: <1163718948.174629.152180@h54g2000cwb.googlegroups.com> Tim Chase wrote: > I can't say I've come across any hosting places that serve up PHP > for $10/yr either...the closest I've found is about $3.50/mo > (which also provides Python CGI). dollar-hosting.net offers php5 and python 2.3, for $10 a year. the-protagonist.net has PHP 4.4 hosting for $10 a year. I'm sure I could find more. Both of those sites use Apache 1.3. From skip at pobox.com Wed Nov 8 11:37:29 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 8 Nov 2006 10:37:29 -0600 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> Message-ID: <17746.1993.906293.522739@montanaro.dyndns.org> Beliavsky> English is a rich language, and there are better ways of Beliavsky> doing that. aahz> Oh, gimme a fucking break. I'm with Beliavsky on this one. I can't see any particular reason to curse in a forum such as c.l.py. It just coarsens the discussion with no obvious positive benefit as far as I can see. Skip From fredrik at pythonware.com Sun Nov 12 19:06:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Nov 2006 01:06:34 +0100 Subject: explicit self revisited In-Reply-To: References: <1163288444.893136.42030@h54g2000cwb.googlegroups.com> <1163315672.921664.306460@e3g2000cwe.googlegroups.com> <1163351573.3497.26.camel@localhost.localdomain> Message-ID: > I suppose that in his view, language advocacy is a zero-sum game, so > positive comments about Python can be considered as FUD against his own > project. He's even invented his own del.icio.us tag for this purpose: > > http://del.icio.us/tag/pythonfud now at: http://del.icio.us/tag/python-fud From george.sakkis at gmail.com Tue Nov 21 14:55:33 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 21 Nov 2006 11:55:33 -0800 Subject: Why is class decorator on method loosing self? References: <1164135863.270437.80340@b28g2000cwb.googlegroups.com> Message-ID: <1164138933.778974.42620@f16g2000cwb.googlegroups.com> George Sakkis wrote: > I don't think you can make it work without resorting to metaclass > magic. At the point of decoration min_max is still a function, not a > method, because class Foo has not been created yet. Here's a way to do > it with a custom metaclass; whether you really want to do it is a > different matter: An improvement to my previous hack: leave memoize as is in the cookbook (extending decoratorargs) and add two lines to decoratorargs: # This would usually be defined elsewhere class decoratorargs(object): def __new__(typ, *attr_args, **attr_kwargs): def decorator(orig_func): self = object.__new__(typ) self.__init__(orig_func, *attr_args, **attr_kwargs) if callable(self): self._customize = lambda cls: MethodType(self, None, cls) return self return decorator Now you don't need memoizefunction and memoizemethod, but you still need the customized metaclass (changed __customize to _customize; name turns to a PITA sooner or later): class CustomizeMeta(type): def __init__(cls, name, bases,dict): for attr,val in dict.iteritems(): if hasattr(val, '_customize'): setattr(cls, attr, val._customize(cls)) #==== examples ============================================= @memoize(3) def fib(n): return (n > 1) and (fib(n - 1) + fib(n - 2)) or 1 class Foo(object): __metaclass__ = CustomizeMeta def __init__(self, i): self._i = i def banner(self): print "Testing method" @memoize(3) def min_max(self, sequence): self.banner() return min(sequence), max(sequence) foo = Foo() print foo.min_max([9,7,5,3,1]) George From researchbase at gmail.com Fri Nov 3 00:04:23 2006 From: researchbase at gmail.com (krishnakant Mane) Date: Fri, 3 Nov 2006 10:34:23 +0530 Subject: a newbi problem: can't find complete python curses library Message-ID: hello, I am a new member to this list. I am Krishnakant from India, Mumbai. I have been coding in python for quite some time and now I am at the intermediate level of programming as far as python is concerned. I am going to develop a accounting software that can work on the console and accessed through ssh from other terminals. I will like to use the curses or ncurses library for the menus and the input forms with add, save, delete, update and cancel buttens. I also need to create drop down menus with a top level menu bar. I read a few articles about python wrapping curses but can't find some thing very comprehencive. my question is, does python possess a complete wrapper to ncurses and its related libraries like menu, panel and form? if yes then where can I find documentation? I read the python documentation and could manage to find out the window object but nothing on menus and panels and forms. thanks and regards. Please help, Krishnakant. From anthra.norell at vtxmail.ch Fri Nov 3 13:22:10 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Fri, 03 Nov 2006 19:22:10 +0100 Subject: ANN: SE 2.3. Available now In-Reply-To: <454B6FEC.20709@islandtraining.com> References: <454B3B49.6070702@vtxmail.ch> <454B6FEC.20709@islandtraining.com> Message-ID: <454B88D2.7050000@vtxmail.ch> Gary Herron wrote: > Frederic Rentsch wrote: > >> A few Cheese Shop upload problems have been solved with the help of this >> creative group. Thank you all! >> >> Version 2.2 beta should be phased out. It has a functional defect, >> missing matches with a very low statistical probability. Version 2.3 has >> this fixed. >> >> Download URL: http://cheeseshop.python.org/pypi/SE/2.3 >> >> > As a matter of polite netiquette, a message like this really ought to > have a paragraph telling us what SE *is*. (Unless it's a secret :-)) > > Thanks for the inquiry. I've been hawking this thing so persistently of late that I'm afraid to start being perceived as a nuisance. SE is a stream editor that is particularly easy and fast to use. A summary of its characteristics is only a click away at the URL a few lines up from this line. Frederic >> A list of possible handling improvements is being made to be >> incorporated in the next version, One major flaw of the interface design >> came to light the other day when a user reported a non-functioning >> Editor Object made with a file name. If the constructor cannot find the >> file it records the fact in the object's log without making the user >> aware that his Editor Object is incomplete or altogether devoid of >> substitutions. His obvious conclusion is that the damn thing isn't >> working right. >> Compile errors should certainly be reported at compile time. The next >> version will send all messages being logged also to stderr by default. >> The thing to do with the current version, if it appears to malfunction, >> is to inspect the log and the compiled substitutions. >> >> >>> Editor = SE.SE ('operators.se') >> >>> Editor.show_log () >> >> Fri Nov 03 12:49:17 2006 - Compiler - Ignoring single word >> 'operators.se'. Not an existing file 'operators.se'. >> >> >>> Editor = SE.SE ('se/operators.se') # path was missing >> >>> Editor.show_log () >> >> (Log is empty. All is well.) >> >> >>> Editor.show (show_translators = 1) >> >> (snip) >> >> Single-Byte Targets >> 1: |<|->|LT| >> 2: |>|->|GT| >> >> Multi-Byte Targets >> 3: |&&|->|AND| >> 4: ||||->|OR| >> >> etc... >> >> The display makes definition errors conspicuous. Missing definitions >> indicate malformed or redefined (overwritten) ones. >> >> >> Frederic >> >> >> >> > > From kbk at shore.net Tue Nov 7 23:31:22 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 7 Nov 2006 23:31:22 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200611080431.kA84VM59025651@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 430 open ( -4) / 3447 closed (+17) / 3877 total (+13) Bugs : 922 open ( -7) / 6316 closed (+31) / 7238 total (+24) RFE : 245 open ( +0) / 241 closed ( +1) / 486 total ( +1) New / Reopened Patches ______________________ modulefinder changes for py3k (2006-10-27) CLOSED http://python.org/sf/1585966 opened by Thomas Heller no wraparound for enumerate() (2006-10-28) CLOSED http://python.org/sf/1586315 opened by Georg Brandl missing imports ctypes in documentation examples (2006-09-13) CLOSED http://python.org/sf/1557890 reopened by theller better error msgs for some TypeErrors (2006-10-29) http://python.org/sf/1586791 opened by Georg Brandl cookielib: lock acquire/release try..finally protected (2006-10-30) http://python.org/sf/1587139 opened by kxroberto Patch for #1586414 to avoid fragmentation on Windows (2006-10-31) http://python.org/sf/1587674 opened by Enoch Julias Typo in Mac installer image name (2006-11-01) CLOSED http://python.org/sf/1589013 opened by Humberto Di?genes Typo in Mac image name (2006-11-01) CLOSED http://python.org/sf/1589014 opened by Humberto Di?genes MacPython Build Installer - Typos and Style corrections (2006-11-02) CLOSED http://python.org/sf/1589070 opened by Humberto Di?genes bdist_sunpkg distutils command (2006-11-02) http://python.org/sf/1589266 opened by Holger The "lazy strings" patch (2006-11-04) http://python.org/sf/1590352 opened by Larry Hastings adding __dir__ (2006-11-06) http://python.org/sf/1591665 opened by ganges master `in` for classic object causes segfault (2006-11-07) http://python.org/sf/1591996 opened by Hirokazu Yamamoto PyErr_CheckSignals returns -1 on error, not 1 (2006-11-07) http://python.org/sf/1592072 opened by Gustavo J. A. M. Carneiro Add missing elide argument to Text.search (2006-11-07) http://python.org/sf/1592250 opened by Russell Owen Patches Closed ______________ Fix for structmember conversion issues (2006-08-30) http://python.org/sf/1549049 closed by loewis Enable SSL for smtplib (2006-09-28) http://python.org/sf/1567274 closed by loewis Mailbox will not lock properly after flush() (2006-10-11) http://python.org/sf/1575506 closed by akuchling urllib2 - Fix line breaks in authorization headers (2006-10-09) http://python.org/sf/1574068 closed by akuchling Tiny patch to stop make spam (2006-06-09) http://python.org/sf/1503717 closed by akuchling modulefinder changes for py3k (2006-10-27) http://python.org/sf/1585966 closed by gvanrossum unparse.py decorator support (2006-09-04) http://python.org/sf/1552024 closed by gbrandl no wraparound for enumerate() (2006-10-28) http://python.org/sf/1586315 closed by rhettinger missing imports ctypes in documentation examples (2006-09-13) http://python.org/sf/1557890 closed by theller missing imports ctypes in documentation examples (2006-09-13) http://python.org/sf/1557890 closed by nnorwitz tarfile.py: better use of TarInfo objects with longnames (2006-10-24) http://python.org/sf/1583880 closed by gbrandl tarfile depends on undocumented behaviour (2006-09-25) http://python.org/sf/1564981 closed by gbrandl Typo in Mac installer image name (2006-11-02) http://python.org/sf/1589013 closed by ronaldoussoren Typo in Mac image name (2006-11-01) http://python.org/sf/1589014 deleted by virtualspirit MacPython Build Installer - Typos and Style corrections (2006-11-02) http://python.org/sf/1589070 closed by ronaldoussoren bdist_rpm not able to compile multiple rpm packages (2004-11-04) http://python.org/sf/1060577 closed by loewis Remove inconsistent behavior between import and zipimport (2005-11-03) http://python.org/sf/1346572 closed by loewis Rational Reference Implementation (2002-10-02) http://python.org/sf/617779 closed by loewis Problem at the end of misformed mailbox (2002-11-03) http://python.org/sf/632934 closed by loewis New / Reopened Bugs ___________________ csv.reader.line_num missing 'new in 2.5' (2006-10-27) CLOSED http://python.org/sf/1585690 opened by Kent Johnson tarfile.extract() may cause file fragmentation on Windows XP (2006-10-28) http://python.org/sf/1586414 opened by Enoch Julias compiler module dont emit LIST_APPEND w/ list comprehension (2006-10-29) CLOSED http://python.org/sf/1586448 opened by sebastien Martini codecs.open problem with "with" statement (2006-10-28) CLOSED http://python.org/sf/1586513 opened by Shaun Cutts zlib/bz2_codec doesn't support incremental decoding (2006-10-29) CLOSED http://python.org/sf/1586613 opened by Topia hashlib documentation is insuficient (2006-10-29) CLOSED http://python.org/sf/1586773 opened by Marcos Daniel Marado Torres scipy gammaincinv gives incorrect answers (2006-10-31) CLOSED http://python.org/sf/1587679 opened by David J.C. MacKay quoted printable parse the sequence '= ' incorrectly (2006-10-31) http://python.org/sf/1588217 opened by Wai Yip Tung string subscripting not working on a specific string (2006-11-02) CLOSED http://python.org/sf/1588975 opened by Dan Aronson Unneeded constants left during optimization (2006-11-02) CLOSED http://python.org/sf/1589074 opened by Daniel ctypes XXX - add a crossref, at least (2006-11-02) CLOSED http://python.org/sf/1589328 opened by Jim Jewett urllib2 does local import of tokenize.py (2006-11-02) http://python.org/sf/1589480 reopened by drfarina urllib2 does local import of tokenize.py (2006-11-02) http://python.org/sf/1589480 opened by Daniel Farina __getattr__ = getattr crash (2006-11-03) CLOSED http://python.org/sf/1590036 opened by Brian Harring Error piping output between scripts on Windows (2006-11-03) http://python.org/sf/1590068 opened by Andrei where is zlib??? (2006-11-04) http://python.org/sf/1590592 opened by AKap mail message parsing glitch (2006-11-05) http://python.org/sf/1590744 opened by Mike python: Python/ast.c:541: seq_for_testlist: Assertion fails (2006-10-31) CLOSED http://python.org/sf/1588287 opened by Tom Epperly python: Python/ast.c:541: seq_for_testlist: Assertion (2006-11-05) CLOSED http://python.org/sf/1590804 opened by Jay T Miller subprocess deadlock (2006-11-05) http://python.org/sf/1590864 opened by Michael Tsai random.randrange don't return correct value for big number (2006-11-06) http://python.org/sf/1590891 opened by MATSUI Tetsushi update urlparse to RFC 3986 (2006-11-05) http://python.org/sf/1591035 opened by Andrew Dalke problem building python in vs8express (2006-11-05) http://python.org/sf/1591122 reopened by thomashsouthern problem building python in vs8express (2006-11-05) http://python.org/sf/1591122 opened by Thomas Southern replace groups doesn't work in this special case (2006-11-06) CLOSED http://python.org/sf/1591319 opened by Thomas K. Urllib2.urlopen() raises OSError w/bad HTTP Location header (2006-11-07) http://python.org/sf/1591774 opened by nikitathespider Undocumented implicit strip() in split(None) string method (2005-01-19) http://python.org/sf/1105286 reopened by yohell Stepping into a generator throw does not work (2006-11-07) http://python.org/sf/1592241 opened by Bernhard Mulder Bugs Closed ___________ python_d python (2006-09-21) http://python.org/sf/1563243 closed by sf-robot glob.glob("c:\\[ ]\*) doesn't work (2006-10-19) http://python.org/sf/1580472 closed by gbrandl structmember T_LONG won't accept a python long (2006-08-24) http://python.org/sf/1545696 closed by loewis T_ULONG -> double rounding in PyMember_GetOne() (2006-09-27) http://python.org/sf/1566140 closed by loewis Different behavior when stepping through code w/ pdb (2006-10-24) http://python.org/sf/1583276 closed by jpe csv.reader.line_num missing 'new in 2.5' (2006-10-27) http://python.org/sf/1585690 closed by akuchling asyncore.dispatcher.set_reuse_addr not documented. (2006-09-20) http://python.org/sf/1562583 closed by akuchling inconsistency in PCALL conditional code in ceval.c (2006-08-17) http://python.org/sf/1542016 closed by akuchling functools.wraps fails on builtins (2006-10-12) http://python.org/sf/1576241 closed by akuchling str(WindowsError) wrong (2006-10-12) http://python.org/sf/1576174 closed by theller does not raise SystemError on too many nested blocks (2006-09-25) http://python.org/sf/1565514 closed by nnorwitz curses module segfaults on invalid tparm arguments (2006-08-28) http://python.org/sf/1548092 closed by nnorwitz "from __future__ import foobar;" causes wrong SyntaxError (2006-08-19) http://python.org/sf/1543306 closed by nnorwitz compiler module dont emit LIST_APPEND w/ list comprehension (2006-10-28) http://python.org/sf/1586448 closed by gbrandl distutils adds (unwanted) -xcode=pic32 in the compile comman (2006-05-19) http://python.org/sf/1491574 closed by nnorwitz codecs.open problem with "with" statement (2006-10-29) http://python.org/sf/1586513 closed by gbrandl suprocess cannot handle shell arguments (2005-11-16) http://python.org/sf/1357915 closed by gbrandl zlib/bz2_codec doesn't support incremental decoding (2006-10-29) http://python.org/sf/1586613 closed by gbrandl missing __enter__ + __getattr__ forwarding (2006-10-20) http://python.org/sf/1581357 closed by gbrandl hashlib documentation is insuficient (2006-10-29) http://python.org/sf/1586773 closed by gbrandl scipy gammaincinv gives incorrect answers (2006-10-31) http://python.org/sf/1587679 closed by loewis string subscripting not working on a specific string (2006-11-02) http://python.org/sf/1588975 closed by gbrandl ctypes XXX - add a crossref, at least (2006-11-02) http://python.org/sf/1589328 closed by theller dict keyerror formatting and tuples (2006-10-13) http://python.org/sf/1576657 closed by gbrandl __getattr__ = getattr crash (2006-11-03) http://python.org/sf/1590036 closed by arigo potential buffer overflow in complexobject.c (2006-10-13) http://python.org/sf/1576861 closed by sf-robot inspect.py imports local "tokenize.py" file (2006-11-02) http://python.org/sf/1589480 closed by loewis python: Python/ast.c:541: seq_for_testlist: Assertion fails (2006-10-31) http://python.org/sf/1588287 closed by nnorwitz python: Python/ast.c:541: seq_for_testlist: Assertion (2006-11-05) http://python.org/sf/1590804 closed by loewis TypeError message on bad iteration is misleading (2005-04-21) http://python.org/sf/1187437 closed by gbrandl replace groups doesn't work in this special case (2006-11-06) http://python.org/sf/1591319 closed by niemeyer unchecked metaclass mro (2006-09-28) http://python.org/sf/1567234 closed by akuchling curses getkey() crash in raw mode (2004-02-09) http://python.org/sf/893250 closed by akuchling RFE Closed __________ Unneeded constants left during optimization (2006-11-02) http://python.org/sf/1589074 closed by loewis From klaus at seistrup.dk Thu Nov 30 09:04:39 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Thu, 30 Nov 2006 14:04:39 +0000 (UTC) Subject: Remarkable results with psyco and sieve of Eratosthenes References: <1164837289.295731.178070@h54g2000cwb.googlegroups.com> Message-ID: Pekka Karjalainen wrote: > You can omit the call to math.sqrt if you test this instead. > > y*y > x > > in place of if y > maxfact: . Or use sqrt = lambda x: x ** .5 Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From sjmachin at lexicon.net Mon Nov 13 06:21:32 2006 From: sjmachin at lexicon.net (John Machin) Date: 13 Nov 2006 03:21:32 -0800 Subject: str.title question after ' In-Reply-To: References: Message-ID: <1163416892.760544.9380@m7g2000cwm.googlegroups.com> Antoon Pardon wrote: > I have a text in ascii. I use the ' for an apostroph. The problem is > this gives problems with the title method. I don't want letters > after a ' to be uppercased. Here are some examples: > > argument result expected > > 't smidje 'T Smidje 't Smidje > na'ama Na'Ama Na'ama > al pi tnu'at Al Pi Tnu'At Al Pi Tnu'at > > > Is there an easy way to get what I want? Depends on your definition of "easy". Writing your own function that will regard the apostrophe as a letter would be "easy" in my book. > > Should the current behaviour condidered a bug? Its limitations could use some documentation. > My would be inclined to answer yes, but that may be > because this behaviour would be wrong in Dutch. I'm > not so sure about english. > It's not very appropriate for English, either: | >>> "didn't".title() | "Didn'T" It's OK for the English way of writing Irish surnames e.g. O'Brien, but not IMHO very good behaviour for anything else. The docs say: "Return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase." Evidently the definition of "word" is the culprit. Doing titlecasing properly depends heavily on the language/locale and what data you are working on. For example, in the UK and anywhere that Scots have migrated in reasonable numbers, you would probably want to do McDonald and MacDonald. Avoiding nonsenses like MacE and MacHin :-) takes some effort and a look-up table, and may not be cost-effective. A related problem: some people mistakenly try too hard to correct perceived data entry errors and also produce nonsenses -- a colleague of Dutch extraction occasionally received mail addressed to Mr O'Belt :-) Cheers, John From john106henry at hotmail.com Thu Nov 30 18:20:24 2006 From: john106henry at hotmail.com (John Henry) Date: 30 Nov 2006 15:20:24 -0800 Subject: Is there an easier way to express this list slicing? In-Reply-To: References: <1164913125.509492.54060@79g2000cws.googlegroups.com> <1164916148.930057.280350@f1g2000cwa.googlegroups.com> <1164916437.055932.193130@79g2000cws.googlegroups.com> <1164917296.255080.149660@j72g2000cwa.googlegroups.com> Message-ID: <1164928824.452080.260110@80g2000cwy.googlegroups.com> Paul McGuire wrote: > "John Henry" wrote in message > news:1164917296.255080.149660 at j72g2000cwa.googlegroups.com... > > > > John Henry wrote: > > > >> > >> Further, if splitUp is a sub-class of string, then I can do: > >> > >> alist, blist, clist, dlist = "ABCDEFGHIJ".slice((1,1,3,None)) > >> > >> Now, can I override the slice operator? > > > > Maybe like: > > > > alist, blist, clist, dlist = newStr("ABCDEFGHIJ")[1,1,3,None] > > > > No need to contort string, just expand on your earlier idea. I changed your > class name to SplitUp to more more conventional (class names are usually > capitalized), and changed slice to __call__. Then I changed the lens arg to > *lens - note the difference in the calling format. Pretty close to what you > have above. Also, reconsider whether you want the __init__ function > list-ifying the input src - let the caller decide what to send in. > In fact, should be possible to make that any object the caller want to send in... > -- Paul > > class SplitUp(object): > def __init__(self,src): > self._src=list(src) > def __call__(self, *lens): > ret = [] > cur = 0 > for length in lens: > if length is not None: > ret.append( self._src[cur:cur+length] ) > cur += length > else: > ret.append( self._src[cur:] ) > return ret > > alist, blist, clist, dlist = SplitUp("ABCDEFGHIJ")(1,1,3,None) > print alist, blist, clist, dlist > > Prints: > ['A'] ['B'] ['C', 'D', 'E'] ['F', 'G', 'H', 'I', 'J'] Thanks for the help, From R.Brodie at rl.ac.uk Thu Nov 16 11:25:40 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 16 Nov 2006 16:25:40 -0000 Subject: Yield References: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> <455b4f9f$1@usenet01.boi.hp.com> <1163659530.752607.120880@m73g2000cwd.googlegroups.com> <455c15ca$1@news.eftel.com> <455c1ddf@news.eftel.com> <1163691173.737911.130410@i42g2000cwa.googlegroups.com> <1163693354.446751.38890@b28g2000cwb.googlegroups.com> Message-ID: "Danny Colligan" wrote in message news:1163693354.446751.38890 at b28g2000cwb.googlegroups.com... > I absoultely agree. Thanks for pointing me out to some real-world > code. However, the function you pointed me to is not a generator > (there is no yield statement... it just returns the entire list of > primes). Oops, should have looked at the code more closely. Another example would be os.walk() in the standard library. From ronrsr at gmail.com Fri Nov 10 12:05:36 2006 From: ronrsr at gmail.com (ronrsr) Date: 10 Nov 2006 09:05:36 -0800 Subject: SyntaxError: Invalid Syntax. In-Reply-To: <1163178099.156160.29280@k70g2000cwa.googlegroups.com> References: <1163178099.156160.29280@k70g2000cwa.googlegroups.com> Message-ID: <1163178336.281812.140580@f16g2000cwb.googlegroups.com> here's some of the surrounding code from the main program: querystring = querystring + " ORDER BY keywords "; #SQL import zsql zc = zsql.connect() print("return from open") zq = zc.query(querystring).dictresult() ronrsr wrote: > no matter where I place this imported file,the statement after it in > the main program gets a syntax error, regardless of the syntax. > > I think I may have changed something in this file, but I'm stuck. Can > anyone help? > > #!/usr/local/bin/python > # Copyright 2004 by Stephen Masterman > > #Change the db connection details here. > > > import MySQLdb > > > > > def connect(): > > > return = MySQLdb.connect (host = "db91x.xxxx.com", > user = "xxxx", > passwd = "xxxxx", > db = "homebase_zingers" > ); From martin at v.loewis.de Thu Nov 30 15:29:16 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 30 Nov 2006 21:29:16 +0100 Subject: Python 2.4 does not marshal infinity floating point properly under Win32 In-Reply-To: <1164917855.809114.184580@j72g2000cwa.googlegroups.com> References: <1164917855.809114.184580@j72g2000cwa.googlegroups.com> Message-ID: <456f3f1c$0$8792$9b622d9e@news.freenet.de> Pierre Rouleau schrieb: > Is this considered an important enough bug to fix it in Python 2.4? To the contrary - it's not considered a bug at all. Python didn't make any promises about "unregular" floating point values, so things like that just may happen. The fix that made Python offer stronger guarantees in 2.5 cannot be ported back to 2.4, since it would break the marshal format of that release. Finally, it's not very likely that *any* additional 2.4.x releases are made at all; only 2.5.x is still actively maintained. Regards, Martin From fredrik at pythonware.com Thu Nov 23 13:56:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Nov 2006 19:56:57 +0100 Subject: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]? In-Reply-To: <4565ED24.3050900@sweetapp.com> References: <4565ED24.3050900@sweetapp.com> Message-ID: Brian Quinlan wrote: >> 4) [] and {} always create a new object every time they're evaluated. > > Not quite. The empty tuple is cached: > > >>> a = () > >>> b = () > >>> a is b > True () isn't [] or {}, though. time to switch to a bigger font? ;-) From vedran at v-programs.com Mon Nov 27 12:35:55 2006 From: vedran at v-programs.com (Croteam) Date: 27 Nov 2006 09:35:55 -0800 Subject: shtoom complicated install Message-ID: <1164648955.446613.66810@l12g2000cwl.googlegroups.com> Hello, I have install problem about shtoom.How to I Install shtoom correct,when I install shtoom with setup.py (shtoom package setup file), it just make some directory (shtoom-0.2) and 3 python files with them.But just tell me this,when I was manual make folder by name "shtoom" (as write in shtoom package setup file) and in that folder put folders: app,audio,multicast,ui ,now I must "insert" python files from shtoom package into that folders but I don't know where I must put every file?? In what folder. I will appreciate any help Regards,Vedran From __peter__ at web.de Fri Nov 10 08:55:01 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Nov 2006 14:55:01 +0100 Subject: announce: FAQs suggested References: <1163166123.773324.126160@m7g2000cwm.googlegroups.com> Message-ID: p.lavarre at ieee.org wrote: > http://effbot.org/pyfaq/suggest.htm has new FAQ's: > > FAQ: How do I ask to exit from a doctest I don't consider that question /frequently/ /asked/ or that feature frequently requested. Also, the KeyboardInterrupt approach is a hack. > FAQ: How do I say unsigned char in ctypes? > FAQ: How do I say returns void in ctypes? That's in the ctypes documentation, where it belongs. Peter From NoelByron at gmx.net Thu Nov 2 03:15:31 2006 From: NoelByron at gmx.net (NoelByron at gmx.net) Date: 2 Nov 2006 00:15:31 -0800 Subject: Thread priority or keeping a (wx)GUI responsive Message-ID: <1162455331.152904.17160@k70g2000cwa.googlegroups.com> I need to do some intense calculations in my application. Those are done by a third party Python library and consume 100% CPU time for some seconds. The computations take place in their own thread to keep my GUI responsive (wxPython in my case). Everything works fine on a dual core machine. On a single CPU machine, the computation slows down the whole GUI (better, the whole machine). The ideal solution in my case would be to give the computation thread a very low priority. But I fear that is not possible? Moving the computations to a different process look quite complex since the result is a large Python data structure. And I fear it would not solve the problem since I can only influence the priority of a subprocess on the windows plattform (I refer to the documentation of the subprocess module). Another possible solution is to include some idle times (time.sleep(0.05) or wxYield() or even better with python yields?) in the algorithm of the computations. Ugly, since I would have to manipulate a third party library. Could sys.setcheckinterval() help? Do I miss something? Any help, tips or advice would be appreciated. Best regards, Noel From fredrik at pythonware.com Fri Nov 10 15:37:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 10 Nov 2006 21:37:58 +0100 Subject: Modules, Packages and Developer Confusion. Oh My! In-Reply-To: <1163190657.792705.55030@m73g2000cwd.googlegroups.com> References: <1163190657.792705.55030@m73g2000cwd.googlegroups.com> Message-ID: dhable at gmail.com wrote: > from model import * > from search import * > > def create_connection(): > # details are unimportant for this example > > > When I try to use the create_connection function in model, I get errors > when I use it as a global function ( just create_connection()). importing everything from "model" into "OPS" isn't the same thing as importing everything from "OPS" into "model". From mnations at gmail.com Fri Nov 10 18:35:25 2006 From: mnations at gmail.com (Mudcat) Date: 10 Nov 2006 15:35:25 -0800 Subject: Tkinter: How do I change the actual width of a widget? Message-ID: <1163201725.520487.176030@i42g2000cwa.googlegroups.com> I am trying to change the width of a widget based on pixel size and not on characters. I can't figure out how to do this. Normally to change to the size of a widget it looks like: widget.configure(width = x) However that is in characters, not in pixels. To retrieve the actual size of a widget, I believe it is done with: x = widget.winfo_width() Obviously that value can not be used in the configure statement. Is there a way to dynamically change the width (and height) of a widget using the winfo data? Thanks, Marc From zhaoqz at gmail.com Thu Nov 9 02:52:46 2006 From: zhaoqz at gmail.com (=?gb2312?B?v9XQxLLL?=) Date: 8 Nov 2006 23:52:46 -0800 Subject: Python to tell what is the IP of my PC In-Reply-To: References: Message-ID: <1163058766.013701.178780@i42g2000cwa.googlegroups.com> >>> import re,urllib2 >>> re.search('\d+\.\d+\.\d+\.\d+',urllib2.urlopen("http://www.hereismyip.com").read()).group() 'xx.xx.xxx.xxx? On 11?9?, ??11?06?, Hieu Hoang wrote: > Hi list, > I think a script to extract the IP from some websites like > whatismyip.com could do the job. I don't know how to write it though, > sure someone can give > direction on that. > > Cheers, > Rooy From http Sun Nov 5 16:15:10 2006 From: http (Paul Rubin) Date: 05 Nov 2006 13:15:10 -0800 Subject: python GUIs comparison (want) References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <1162657420.655675.185930@e3g2000cwe.googlegroups.com> <454d73ab@quokka.wn.com.au> <1162708081.974808.283370@i42g2000cwa.googlegroups.com> <7xy7qql7i7.fsf@ruckus.brouhaha.com> <1162747326.717224.236010@i42g2000cwa.googlegroups.com> Message-ID: <7xmz75ioip.fsf@ruckus.brouhaha.com> "Mudcat" writes: > > No that would suck. Best to try to stay as close as possible to the > > native widgets on whatever the underlying platform is. If you want > > to depart from the native UI, then start from scratch and write a whole > > new window system with a complete app suite etc. > > Ok. But other than thinking it would suck, you're basically repeating > my point about starting from scratch with a whole new suite of widgets. No. In both cases I'm saying stick with a consistent set of widgets and visual look across all applications. Either use your OS's existing widget set and make your apps look like the existing apps for that OS, or else throw out all those apps and write a whole new set whose look is new, but is consistent across all of them. > Sometimes you want a tool that blends in. Sometimes you want one that > stands out, especially when you're competing against other tools where > they all kind of look the same. This is what I'm saying would suck. Maybe the standing-out would get more attention but it's a nuisance for users. From ynaddaf at riptown.com Tue Nov 7 17:55:51 2006 From: ynaddaf at riptown.com (deLenn) Date: 7 Nov 2006 14:55:51 -0800 Subject: Finding Nonzero Elements in a Sparse Matrix In-Reply-To: <1162939218.006857.100300@h54g2000cwb.googlegroups.com> References: <1162937813.360645.3040@h54g2000cwb.googlegroups.com> <1162939218.006857.100300@h54g2000cwb.googlegroups.com> Message-ID: <1162940151.208051.125810@k70g2000cwa.googlegroups.com> Thanks for the reply. 'nonzero' deos not seem to work with sparse matrices. here is an example: from scipy import * A = sparse.lil_matrix((3,3)) A[1,2] = 10 A[2,0] = -10 nonzero(A) >>> () (I tried it with an ordinary matrix, and it works fine) Cheers. Nick Vatamaniuc wrote: > The function you might want is nonzero() or flatnonzero() > > >>> from numpy import * > > >>> a=array([ [1,2],[0,4] ]) > > >>> a > array([[1, 2], > [0, 4]]) > > >>> flatnonzero(a) > array([0, 1, 3]) > > nonzero() will return the a sequence of index arrays of non zero > elements > flatnonzero() returns the non-zero elements of the flattened version > of the array. > > Cheers, > Nick Vatamaniuc > > > > deLenn wrote: > > Hi, > > > > Does scipy have an equivalent to Matlab's 'find' function, to list the > > indices of all nonzero elements in a sparse matrix? > > > > Cheers. From robert.kern at gmail.com Sun Nov 26 00:52:19 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 25 Nov 2006 23:52:19 -0600 Subject: About alternatives to Matlab In-Reply-To: <1164518610.895461.252690@45g2000cws.googlegroups.com> References: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> <1163711343.870829.110030@h48g2000cwc.googlegroups.com> <1163720268.611923.3180@e3g2000cwe.googlegroups.com> <1164331082.270046.290720@l39g2000cwd.googlegroups.com> <1164504562.834005.197830@l39g2000cwd.googlegroups.com> <1164518610.895461.252690@45g2000cws.googlegroups.com> Message-ID: Phil Schmidt wrote: > sturlamolden wrote: > >> Using Python just for the sake of using Python is silly. > > Well, that kind of gets right to my point. Does the "added" effort with > Python to interface with data acquisition hardware really result in > less productivity? I am very familiar with Matlab, Labview, and Python, > and frankly, Python is the most productive and powerful programming > language of the three. But it's the hardware compatibility thing that > concerns me with Python. Without knowing the hardware that you want to use, it's quite difficult for us to tell you anything useful. Most likely, you're simply going to have to sit down with a list of the hardware that you want to use, the existing solutions for interfacing with that hardware (e.g. already written MATLAB, LabView, or Python extension modules for that hardware), and their costs. You're going to have to weigh those costs against the cost of using ctypes or something similar to wrap the raw DLLs if a Python extension module isn't available. We might be able to help you locate the already-existing Python wrappers for your hardware, but the rest are judgement calls that only you can make. To make an accurate judgement, you will probably need to have a little bit of experience trying to wrap one such raw DLL. If you can't afford the time to do that one experiment, then you probably have your answer. -- 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 timr at probo.com Fri Nov 17 02:16:11 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 17 Nov 2006 07:16:11 GMT Subject: how to print pdf with python on a inkjet printer. References: Message-ID: "krishnakant Mane" wrote: > >hello all. >I am developing an ncurses based python application that will require >to create pdf reports for printing. >I am not using py--qt or wx python. >it is a consol based ui application and I need to make a pdf report >and also send it to a lazer or ink jet printer. >is it possible to do so with python? Making the PDF is easy. Go get ReportLab from www.reportlab.org. I consider it the best Python PDF solution. Printing is more complicated, because you actually need something that can RENDER the PDF. The most common such renderer is the Acrobat Reader, and you can actually call the Acrobat Reader from a command line with a parameter that tells it to print the file automatically. The only disadvantage is that using that method will only print to the "default" printer. >or is it that I will have to use the wxpython library asuming that >there is a print dialog which can open up the list of printers? Even if you got the list of printers, what would you do with it? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From srikrishnamohan at gmail.com Tue Nov 14 08:07:50 2006 From: srikrishnamohan at gmail.com (km) Date: Tue, 14 Nov 2006 18:37:50 +0530 Subject: __init__.py In-Reply-To: References: Message-ID: Hi, wow ! i tried it and it works like charm! could access variables declared at root module dir in submodules. also i would like to know if i can have an abstract class declared in __init__.py with common variables ? regards, KM On 11/14/06, Fredrik Lundh wrote: > > "km" wrote: > > > I have a structure like this : > > foo/__init__.py > > foo/bar/__init__.py > > foo/bar/firstmodule.py > > foo/abc/__init__.py > > foo/abc/secondmodule.py > > > > now i have some variables (paths to data files) common, to be used in > > first module and second modules respectively. > > can i set those variables in foo/__init__.py so that i can access them > by > > foo.mypath1 in first and second submodule class definitions? > > looks ok to me, as long as you remember to actually import foo into your > submodules. > > have you tried it? > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dynamicdestroyer at yahoo.de Wed Nov 15 12:13:59 2006 From: dynamicdestroyer at yahoo.de (Mateuszk87) Date: 15 Nov 2006 09:13:59 -0800 Subject: Yield Message-ID: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> Hi. may someone explain "yield" function, please. how does it actually work and when do you use it? thanks in forward mateusz From beliavsky at aol.com Mon Nov 6 21:20:01 2006 From: beliavsky at aol.com (Beliavsky) Date: 6 Nov 2006 18:20:01 -0800 Subject: Pyro stability References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <454dd84b$0$328$e4fe514c@news.xs4all.nl> <1162783631.291535.221530@f16g2000cwb.googlegroups.com> <454fdbc5$0$335$e4fe514c@news.xs4all.nl> Message-ID: <1162866001.849724.245510@b28g2000cwb.googlegroups.com> Carl J. Van Arsdall wrote: > Pyro is fucking amazing and has been a great help to a couple of our projects. You should watch your language in a forum with thousands of readers. From bearophileHUGS at lycos.com Thu Nov 2 09:21:10 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Nov 2006 06:21:10 -0800 Subject: other ways to check for ? In-Reply-To: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> Message-ID: <1162477269.980535.202320@h48g2000cwc.googlegroups.com> elderic: > 1.: --> sort of clumsy and discouraged by the docs as far as I read > import types > type(f) is types.FunctionType What's the problem with this? from types import FunctionType if isinstance(f, FunctionType): ... Bye, bearophile From anthra.norell at vtxmail.ch Sat Nov 4 03:00:50 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Sat, 04 Nov 2006 09:00:50 +0100 Subject: ANN: SE 2.3. Available now In-Reply-To: References: <454B3B49.6070702@vtxmail.ch> <454B6FEC.20709@islandtraining.com> <454B8B8D.8010406@vtxmail.ch> Message-ID: <454C48B2.3090801@vtxmail.ch> Fredrik Lundh wrote: > Frederic Rentsch wrote: > > >> And here's the proof I am being perceived as a nuisance. I apologize, >> keeping to myself that I don't care. >> > > since you're constantly targeting newbies, and are hawking your stuff > also for things for which there are simple and efficient solutions > available in Python's standard library, your behavior could be seen > as more than just a nuisance. > > > > Thank you for making me aware of it. I totally agree with you that inefficient complexity should never replace efficient simplicity. SE, in fact, is much more a convenient interface complement than a stand-alone tool and as such meant to cooperate with the available Python idiom. I used this forum to connect with real-life problems, which I believe is one of its main purposes. Testing the envelope of my 'stuff' I would almost certainly have overstretched it on occasion. And again, what's wrong with this absolutely normal development process? And what better environment could there be for it than an interest group like this one where experts like yourself offer direction? I am not targeting newbies (whatever that is). I am not targeting at all. I invite response. You had cause to respond as this message of yours reveals. But you didn't respond and now your are angry with me for it. So, thanks again for the information. Your comments are always welcome. I understand your style as an expression of your personality. Belligerence passes my notice if I don't see what I have to do with it. Regards Frederic From gagsl-py at yahoo.com.ar Mon Nov 20 20:10:09 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 20 Nov 2006 22:10:09 -0300 Subject: Programmatically replacing an API for another module In-Reply-To: <5ni4m291t9ctfsgisus67a5q6gv7blvsjj@4ax.com> References: <39ednaWIOuxepv_YnZ2dnUVZ_omdnZ2d@comcast.com> <5ni4m291t9ctfsgisus67a5q6gv7blvsjj@4ax.com> Message-ID: <7.0.1.0.0.20061120220424.040e8fd8@yahoo.com.ar> At Monday 20/11/2006 21:52, Tom Plunket wrote: >What I ran into after posting is that I don't know how to get the >__dict__ for the module's scope; is it available? I.e. I can do >'print os.path.__dict__', but 'print __dict__' at module scope results >in a NameError since __dict__ is undefined at that scope. However, if >I could do 'os.path = local_module' somehow, I'd be getting basically >what I want. Maybe I could just have a my_os_path.py, and in my test >code import it as os.path, and then the other code would see that >os.path is already loaded and not bother doing so again? Haven't >tried it, am interested in the answer, but I do have enough to work >with for now... Replacing a module in this way also ensures that I'm >only calling the parts of the API that I intend to call, which is a >handy side-effect. You can do this: import my_os_path os.path = my_os_path That shows also that you can use the module as its own namespace. No need to use __dict__ explicitely. dir(module) gives you the names defined in the module. From inside the module self, use globals(). -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From john106henry at hotmail.com Wed Nov 8 14:49:07 2006 From: john106henry at hotmail.com (John Henry) Date: 8 Nov 2006 11:49:07 -0800 Subject: How to choose the right GUI toolkit ? In-Reply-To: <455226c0$0$17087$c3e8da3@news.astraweb.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> Message-ID: <1163015347.164393.74110@i42g2000cwa.googlegroups.com> John Salerno wrote: > Dan Lenski wrote: > > > So, is there another toolkit I should be looking at? > > I highly recommend wxPython. It's very mature, full-featured, and > portable, and fairly easy to learn as well. I can't really compare it to > other toolkits (not having used any of them, except Tkinter), but it's > definitely one of the most popular and well-supported ones out there. > > http://www.wxpython.org/ I highly recommend that you try PythonCard (which sits on top of wxPython). You can get productive very very quickly. Take a look at: http://pythoncard.sourceforge.net/walkthrough1.html From Leo.Kislov at gmail.com Thu Nov 2 21:29:35 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 2 Nov 2006 18:29:35 -0800 Subject: How to test python extension modules during 'make check' / 'make distcheck'? References: <1ho79n0.1ui6ozx1bxjznkN%asbach@ient.rwth-aachen.de> Message-ID: <1162520975.593351.76880@f16g2000cwb.googlegroups.com> Mark Asbach wrote: > Hi pythonians, > > I'm one of the maintainers of an open source image processing toolkit > (OpenCV) and responsible for parts of the autotools setup. The package > mainly consists of four shared libraries but is accompanied by a python > package containing some pure python code and of course extension modules > for the four libraries. > > Now during the last month we were preparing a major release which means > testing, fixing, testing, fixing, ... in the first degree. Typical > functionality of the shared libraries is verified during 'make check' > and 'make distcheck' by binaries that are linked against the libraries > (straight forward) and are listed in the 'TESTS' automake primary. > > Unfortunately, many problems with the python wrappers arose from time to > time. Currently we have to build and install before we can run any > python-based test routines. When trying to integrate python module > testing into the automake setup, there are some problems that I couldn't > find a solution for: > > a) the extension modules are built in different (other) subdirectories - > so they are not in the local path where python could find them As I understand it's not python that cannot find them but dynamic linker. On ELF UNIX systems you can set LD_LIBRARY_PATH to help linker find dependencies, on Windows -- PATH. If you need details, you can find them in dynamic linker manuals. > b) the libraries and extension modules are built with libtool and may > have rpaths compiled in (is this problematic)? libtools seems to have some knobs to cope with rpath: http://sourceware.org/ml/bug-glibc/2000-01/msg00058.html > c) a different version of our wrappers might be installed on the testing > machine, somewhere in python/site-packages. How can I make sure that > python only finds my 'new' local generated modules? Set PYTHONPATH to the directory where locally generated modules are located. They will be found before site packages. -- Leo From steve at holdenweb.com Fri Nov 10 13:39:07 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Nov 2006 12:39:07 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: <4rhku3FriokeU2@mid.individual.net> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Michael Hobbs wrote: > >> That is, assume that the expression ends at the colon, not at the >> newline. That would make this type of statement possible: >> if color == red or >> color == blue or >> color == green: >> return 'primary' >> Right now, such a statement would have to be spelled thus: >> if color == red or \ >> color == blue or \ >> color == green: >> return 'primary' >> or >> if (color == red or >> color == blue or >> color == green): >> return 'primary' > > What about > > if color == red or blue or green: > return 'primary' > > :) > > Really, I think it'd be more mess to let the if statement's end only > depend on ":". I think there could arise situations that are messy > to debug. If I need multiple lines I prefer the parentheses. > I still prefer if color in (red, blue, green): ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From johnzenger at gmail.com Sun Nov 26 21:36:27 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 26 Nov 2006 18:36:27 -0800 Subject: Ruby/Python/REXX as a MUCK scripting language References: <2006112418112116807-zobeid@techiecom> Message-ID: <1164594987.770839.251450@n67g2000cwd.googlegroups.com> Have you considered JavaScript Spidermonkey or JavaScript Rhino? Sandboxing is automatic, and lots of people know the language already (although fewer people are familiar with its dynamic object-oriented capabilities). Tony Belding wrote: > I'm interested in using an off-the-shelf interpreted language as a > user-accessible scripting language for a MUCK. I'm just not sure if I > can find one that does everything I need. The MUCK must be able to > call the interpreter and execute scripts with it, but the interpreter > must also be able to call functions in the MUCK code. And then there's > the security issue that really worries me. . . I have to be able to > limit what the interpreter can execute. I can't have my users running > scripts that access the console, access the filesystem or sockets > directly, or call libraries or other binaries outside the MUCK. > > Is this practical? I'm thinking of Ruby or Python for this, if they > can meet the requirements. > > I might even consider REXX. . . I remember ARexx from my Amiga days, > and how great it was for string manipulation and application scripting. > However. . . My immediate target platform, Mac OS X, comes with Ruby > and Python but not REXX, so that's a disadvantage. > > My final option would be to create my own language interpeter where I > have control over everything that happens. That is what MUCKs have > always done in the past. But the result was always quirky, limited > languages like MUF (Multi-User Forth) which really turn off a lot of > coders. Furthermore, I've never created a language before, and it > would be a lot of extra work for me. > > -- > Tony Belding, Hamilton Texas From nick at craig-wood.com Wed Nov 29 06:30:06 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 29 Nov 2006 05:30:06 -0600 Subject: Really closing stdout (was: "fork and exit" needed?) References: <8osmm21skionildtnme1j0nvqbla6oqk72@4ax.com> Message-ID: Mitja Trampus wrote: > Nick Craig-Wood wrote: > > I'm not sure how you do open stdout to /dev/null in python though! > > I suspect something like this... > > import posix > > posix.close(1) > > posix.open("/dev/null", posix.O_WRONLY) > > Yes, you're close enough... The explanations are here: > http://www.google.com/search?q=python%20close%20stdout, > I like this one in particular: > http://www.python.org/infogami-faq/library/why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it/ > > If you explicitly want to leave file descriptors 0-2 present > (Do you gain anything by not closing them? If you know, do > tell...), It is traditional I think... >From the unix FAQ, http://www.erlenstar.demon.co.uk/unix/faq.txt :- 6. `close()' fds 0, 1, and 2. This releases the standard in, out, and error we inherited from our parent process. We have no way of knowing where these fds might have been redirected to. Note that many daemons use `sysconf()' to determine the limit `_SC_OPEN_MAX'. `_SC_OPEN_MAX' tells you the maximun open files/process. Then in a loop, the daemon can close all possible file descriptors. You have to decide if you need to do this or not. If you think that there might be file-descriptors open you should close them, since there's a limit on number of concurrent file descriptors. 7. Establish new open descriptors for stdin, stdout and stderr. Even if you don't plan to use them, it is still a good idea to have them open. The precise handling of these is a matter of taste; if you have a logfile, for example, you might wish to open it as stdout or stderr, and open `/dev/null' as stdin; alternatively, you could open `/dev/console' as stderr and/or stdout, and `/dev/null' as stdin, or any other combination that makes sense for your particular daemon. > but pointing do /dev/null, you could do: > > null = os.open(os.devnull,os.O_WRONLY) > os.dup2(null,0) > os.dup2(null,1) > os.dup2(null,2) > os.close(null) > > Untested. Ah, dup2() was on the tip of my mind's tongue ;-) You could write it like this, and then it even works on Windows! import os import sys import time print os.getpid() null = os.open(os.devnull,os.O_RDWR) os.dup2(null, sys.stdin.fileno()) os.dup2(null, sys.stdout.fileno()) os.dup2(null, sys.stderr.fileno()) os.close(null) print "You won't see this" print >>sys.stderr, "Or this" time.sleep(60) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From xi at gamma.dn.ua Sun Nov 19 09:38:03 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Sun, 19 Nov 2006 16:38:03 +0200 Subject: A python IDE for teaching that supports cyrillic i/o In-Reply-To: <1knc9a9960uon.slnj7e17d24m$.dlg@40tude.net> References: <1knc9a9960uon.slnj7e17d24m$.dlg@40tude.net> Message-ID: <20061119143803.GC12399@58sirius016.dc.ukrtel.net> On Sun, Nov 19, 2006 at 03:13:30PM +0100, Alan Franzoni wrote: > Kirill Simonov si ? divertito a scrivere: > > > On Sun, Nov 19, 2006 at 12:33:39PM +0100, Alan Franzoni wrote: > > > No, I would prefer the editor to save the .py files with non-ASCII > > characters in UTF-8 encoding adding the BOM at the beginning of the > > file. This will allow the interpreted to detect the file encoding > > correctly and would save a teacher from explaining what an encoding is > > and why it is needed. > > You'll run into encoding problems anyway in your programmer's life. I don't > think it's a workaround, try this article: > > http://www.joelonsoftware.com/articles/Unicode.html > > I think it's highly useful, you could tell that to your students. Please remember that most of the students will not become professional programmers. Personally I think that encoding problems are nightmare in general, and in Python in particular, and would like to avoid explaining it as longer as possible. Besides, it won't be me, it will be a teacher who will explain it, and the teacher themself might have a vague notion about this topic. > Eclipse+Pydev seems to work with that. I'm not able to check with other > editors right now, but it seems you're experiencing a simple encoding > problem; your editor doesn't know which encoding you'd like to use, so it > defaults to ascii or iso-8859-1 leading to such problems. No, my problem is that the emulation of sys.stdin/sys.stdout under an IDE's interactive console doesn't work like the real sys.stdin/sys.stdout under a real terminal. Thanks, Kirill. From jm.suresh at gmail.com Fri Nov 3 01:11:01 2006 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 2 Nov 2006 22:11:01 -0800 Subject: Best way to have intermediate object description format Message-ID: <1162534260.948002.59780@h48g2000cwc.googlegroups.com> Hi, Is there any standard text format for storing data of object oriented nature. The text file should be readable. That is, Is there any better way than having to write out a file like this from the original place and read it in python and process it. #---------------------------- world = World(name='MyWorld') world.objects.append(Box(color='red')) world.objects.append(Circle(color='green')) world.someProp = "123" #----------------------------- Thanks. Suresh From gagsl-py at yahoo.com.ar Thu Nov 9 18:53:51 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 09 Nov 2006 20:53:51 -0300 Subject: Having problems with urlparser concatenation In-Reply-To: <1163114626.595813.286260@b28g2000cwb.googlegroups.com> References: <1163114626.595813.286260@b28g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061109204327.058fac38@yahoo.com.ar> At Thursday 9/11/2006 20:23, i80and wrote: >I'm working on a basic web spider, and I'm having problems with the >urlparser. >[...] > SpliceStart = Website.find('', SpliceStart)) > > ParsedURL = >urlparse((Website[SpliceStart+9:(SpliceEnd+1)])) > robotparser.set_url(ParsedURL.hostname + '/' + >'robots.txt') >----- >Traceback (most recent call last): > File "C:/Documents and Settings/Andrew/Desktop/ScoutCode-0.09.py", >line 120, in > FindLinks(Website) > File "C:/Documents and Settings/Andrew/Desktop/ScoutCode-0.09.py", >line 84, in FindLinks > robotparser.read() > File "C:\Program Files\Python25\lib\robotparser.py", line 61, in read > f = opener.open(self.url) > File "C:\Program Files\Python25\lib\urllib.py", line 190, in open > return getattr(self, name)(url) > File "C:\Program Files\Python25\lib\urllib.py", line 451, in >open_file > return self.open_local_file(url) > File "C:\Program Files\Python25\lib\urllib.py", line 465, in >open_local_file > raise IOError(e.errno, e.strerror, e.filename) >IOError: [Errno 2] The system cannot find the path specified: >'en.wikipedia.org\\robots.txt' > >Note the last line 'en.wikipedia.org\\robots.txt'. I want >'en.wikipedia.org/robots.txt'! What am I doing wrong? No, you don't want 'en.wikipedia.org/robots.txt'; you want 'http://en.wikipedia.org/robots.txt' urllib treats the former as a file: request, here the \\ in the normalized path. You are parsing the link and then building a new URI using ONLY the hostname part; that's wrong. Use urljoin(ParsedURL, '/robots.txt') instead. You may try Beautiful Soup for a better HTML parsing. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From paolopantaleo at gmail.com Mon Nov 6 08:03:54 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Mon, 6 Nov 2006 14:03:54 +0100 Subject: Building C extensions Message-ID: <83e8215e0611060503w123eb1cat56f5e086d2b8d2d@mail.gmail.com> Well I'm just courious: if I want to buid a C extension, I shoul use the same compiler that has been used to build python (right?). Since python has been built using Visual C, how can I build an extension if I don't have Visual Studio? PAolo From robert.kern at gmail.com Thu Nov 2 13:46:37 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 02 Nov 2006 10:46:37 -0800 Subject: Python in sci/tech applications In-Reply-To: <1162491753.605134.162700@i42g2000cwa.googlegroups.com> References: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> <1162489638.013433.102180@h48g2000cwc.googlegroups.com> <1162491753.605134.162700@i42g2000cwa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Robert Kern: >> We distribute mingw set up to do this with our "Enthought >> Edition" Python distribution. >> http://code.enthought.com/enthon/ > > Sorry, maybe I'm blind but I don't see MinGW listed in that page... > Maybe it's included but not listed... It's there. -- 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 inq1ltd at verizon.net Fri Nov 24 16:56:58 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Fri, 24 Nov 2006 16:56:58 -0500 Subject: Access to variable from external imported module In-Reply-To: <1164393677.496060.174120@f16g2000cwb.googlegroups.com> References: <1164316786.875306.276460@h54g2000cwb.googlegroups.com> <1164393677.496060.174120@f16g2000cwb.googlegroups.com> Message-ID: <0J99003UJ88QKFR0@vms048.mailsrvcs.net> On Friday 24 November 2006 13:41, John Machin wrote: > jim-on-linux wrote: > > On Friday 24 November 2006 03:30, John Machin > > > > wrote: > > > jim-on-linux wrote: > > > > GinTon, > > > > > > > > I think this is what you want. > > > > > > > > > > > > class Kdoi: > > > > > > Is that a typo? > > > > No, it's a style. life seems to be > > easier to me if one is consistent, all my > > classes begin with K. > > and end with "i"? > > > > > def __init__(self) : > > > > self.Fdo() > > > > > > What is all this K and F stuff? > > > > It's my style. life seems to be easier to > > me if one is consistent all my function begin > > with F. > > You left out a word; the correct way of > phrasing that is: "All my function _are_ begin > with F" :-) No, for Non-Hungrian programmers it's "all-ah me" Functions gona begin witha F, not Func. anda "all-ah-me" classes gona begin witha K, not Klas. Anda only me gona Know the Fdiff cause me codea is not opena. Anda I finda that it savea me time causea I doa thisa way fora a longa time. Whena I gonna hava to changea maybe I willa. > > This appears to be a variation on "Hungarian > notation"; google that for opinions pro & con. > > In a certain vernacular, it would be called "an > effed concept" :-) > > > I started doing things like this when the > > only way to debug was to read each line of > > code and try to figgure out if it was the > > problem. > > When was that? That was when bill gates just left Harvard, basic was brand new, and 4k of memory was installed free when you bought a computer, (TRS80), my first,. Assemble was the alternative to Basic and you had to backup on tape because floppies didn't exist. And, most people on this site wern't even a gleem in their fathers eye. > Even years ago, there were > slightly better ways. For example, my first > boss' boss was an enthusiastic coder and > debugger and also a workaholic. Colleagues who > lived along the same railway line as he and > were foolish enough not to hide behind a > newspaper could have their morning or evening > reverie disturbed by a cry of "Glad you're > here! I'll hold the listing, you hold the > dump!". I get the impression that debugging > techniques have moved along a little bit since > then. :-) > > > They are my personal sign posts. > > > > > > def Fdo(self): > > > > > > > > > > > > searchterm = 'help' > > > > print searchterm #local > > > > > > > > self.searchterm = searchterm > > > > print self.searchterm #used inside > > > > the class > > > > > > > > Kdo.searchterm = searchterm #<<<< > > > > print Kdo.searchterm #used outside > > > > the class Kdomore() > > > > > > > > > > > > > > > > class Kdomore(Kdo): > > > > def __init__(self) : > > > > self.Fdomore() > > > > > > > > def Fdomore(self): > > > > searchterm = Kdo.searchterm # > > > > <<<< print searchterm > > > > > > It's not apparent what the print statements > > > are for -- are they part of an attempt to > > > debug your code? > > > > print shows the results wherever a print > > statement turns up the results = 'help' . > > I didn't run the code, and it has it has a > > coding error > > I noticed. > > > but if removed, the results should be; > > > > searchterm = 'help' > > self.searchterm = 'help' > > Kdo.searchterm = 'help' Correct but when writing one must be clear. Would it be better for me to write, your question above was Is that a typo? Or is it better if I were to write, your question above, "Is that a typo?", is a legimate question, but not clear. So, to be clear one might write is "Kdoi" correct?. A clear response would be, it is not "Kdoi", it is "Kdo". But that's not correct either, it is Kdo. If one runs the code I don't expect the user to look for "help", I think we will see help and will THINK that the results are correct. THINK is also incorrect, it should be written. think, or should it? > No, the result would be > help > help > help > > Plug in a text-to-speech module and a phone > dialer and you're done ;-) > > > Sound silly but many people have trouble > > with getting a variable from here to there in > > their code. This shows that it can be done > > > > > What gives you the idea that this is what > > > the OP wants or needs? > > > > If I remember right, he refrased his first > > question and asked a second one. > > Sometimes people don't take the time to write > > correctly, the questions that are really in > > their mind. So I guessed. If Im wrong, he > > will ignore it. If I'm right, he will use > > it. > > With luck. Kindly consider another possibility: > that you are wrong (or just marching to the > beat of your own tambourine) and he (or she) is > a newbie & will use it :-) > "Because he being of course judge of that tendency will make his opinions the rule of judgment, and approve or condemn the sentiments of others only as they shall square with or differ from his own?" Thomas Jefferson I enjoied this, but time is money, jim-on-linux http://www.inqvista.com From paul.keating at nibc.com Fri Nov 10 09:59:28 2006 From: paul.keating at nibc.com (paul.keating at nibc.com) Date: 10 Nov 2006 06:59:28 -0800 Subject: Need help with Subversion bindings Message-ID: <1163170768.284700.95640@e3g2000cwe.googlegroups.com> I'm trying to write a basic Subversion client because I need to integrate Subversion with a product that keeps source code in a database (so it has no notion of "working copy"). I have tried to translate the simple C examples in Garrett Rooney's book into Python, but the very clever SWIG stuff has made the Python access so different from the corresponding C that I can't do it. Example: I can create an apr array but I have no idea how to insert something into it. In C you use APR_ARRAY_PUSH. In Python that doesn't exist. Another example: I can create an apr hash, but I can't work out how to look inside it. In C it is a struct with members count and max etc. In Python it is a class that doesn't remotely resemble the struct. Has anyone got a bare-bones bit of working Python that shows how to do (say) an add or a checkout? There is an example of status in the Subversion book but it's a toy: it doesn't show how you create an authentication callback so it will only work locally. From horpner at yahoo.com Fri Nov 10 15:02:04 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Nov 2006 21:02:04 +0100 Subject: comparing Unicode and string References: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> <1161281095.174018.223790@f16g2000cwb.googlegroups.com> <1161595714.342067.51350@e3g2000cwe.googlegroups.com> <1163120577.369133.279080@h48g2000cwc.googlegroups.com> Message-ID: On 2006-11-10, Steve Holden wrote: >>> But I don't insist on my PEP. The example just shows just >>> another pitfall with Unicode and why I'll advise to any >>> beginner: Never write text constants that contain non-ascii >>> chars as simple strings, always make them Unicode strings by >>> prepending the "u". >> >> That doesn't do any good if you aren't writing them in unicode >> code points, though. > > You tell the interpreter what encoding your source code is in. > It then knows precisely how to decode your string literals into > Unicode. How do you write things in "Unicode code points"? for = u"f\xfcr" -- Neil Cerutti From sp1d3rx at gmail.com Thu Nov 30 19:19:36 2006 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 30 Nov 2006 16:19:36 -0800 Subject: XML blooming In-Reply-To: <1164864927.746788.125390@j44g2000cwa.googlegroups.com> References: <1164864927.746788.125390@j44g2000cwa.googlegroups.com> Message-ID: <1164932375.975244.60460@l12g2000cwl.googlegroups.com> Concerning #2, Microsoft has released a tool for XSD Inference. It can't generate the exact XSD file, but it can guess what it was... http://download.microsoft.com/download/8/0/f/80fca9f1-292e-4b50-b512-ccf004d4b58e/xsdinference.exe Paddy wrote: > (That is bloom as in http://www.wmhelp.com/xmlpad2.htm ;-) > > Suddenly, OK, over a number of months, our design environment at work > has sprouted a wealth of XML configuration files, DTD's etc. The time > has come when I need to loose my XML cherry. > So , I guess I need to learn Elementtree. > > In supporting our design environment I think I will need > 1) An editor that can read in a DTD or XML Schema Definition, (XSD), > as well as an XML file, and help me to write conforming XML. > 2) A tool to extract an XSD from XML examples. > > Hmm, I'm also thinking about a Python project along the lines of > something that could translate between the world of the Traits package > (http://code.enthought.com/traits/), and XSD/DTD/XML. Has anyone done > this before? > > Thanks in advance, Paddy. From dlenski at gmail.com Thu Nov 9 19:06:37 2006 From: dlenski at gmail.com (Dan Lenski) Date: 9 Nov 2006 16:06:37 -0800 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> Message-ID: <1163117197.206946.159890@i42g2000cwa.googlegroups.com> Ben Finney wrote: > > I think the colon could be omitted from every type of compound > > statement: 'if', 'for', 'def', 'class', whatever. Am I missing > > anything? > > A use case. What problem is being solved by introducing this > inconsistency? I agree completely. And as a recent convert to Python, I have to say that I *like* the colons. I found the whitespace-and-colon thing really irritating... for about 2 hours. The colon makes it easier to eyeball where a block statement begins in the absence of braces around the block, it allows one-line if statements (which I use a lot), and it means that even the stupidest, simplest editor can figure out where auto-indentation is needed, namely following any line that ends with a colon (except in a triple-quoted, I guess). Contrast that with Perl, where in years of professional and hobby use I have not found a single editor that gets indentation right more than about 90% of the time. The syntax is too darn complicated. With Python, figuring out where to auto-indent is trivial. Works for me. Dan From fredrik at pythonware.com Sat Nov 4 08:37:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 04 Nov 2006 14:37:50 +0100 Subject: py2exe questions In-Reply-To: <1162646535.744282.95290@m7g2000cwm.googlegroups.com> References: <454BB574.9030607@websafe.com> <1162646535.744282.95290@m7g2000cwm.googlegroups.com> Message-ID: Jerry wrote: > Despite what everyone is saying though, I believe that any and all > solutions will require that the byte-code be extracted to some > directory before being run. the Python interpreter doesn't really care what you believe, though; it's perfectly capable of executing byte code that's stored in memory buffers. From larry.bates at websafe.com Tue Nov 21 10:05:51 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 21 Nov 2006 09:05:51 -0600 Subject: Programmatically replacing an API for another module In-Reply-To: <5ni4m291t9ctfsgisus67a5q6gv7blvsjj@4ax.com> References: <39ednaWIOuxepv_YnZ2dnUVZ_omdnZ2d@comcast.com> <5ni4m291t9ctfsgisus67a5q6gv7blvsjj@4ax.com> Message-ID: <456315CF.8070705@websafe.com> > Depends on what all I'm mocking. If I'm mocking an expensive service > across the internet that is time consuming to connect to, or even > mocking a well-defined system API call that is similarly time > consuming to call, then I can stub something in that doesn't do > anything but validate the arguments. Additionally, I can "document" > the caveats and possibly-errant behavior with my mock, and > subsequently get automatic testing that I'm dealing with API bugs > properly. When I find myself doing what you describe, I often introduce a "testing" mode switch into the equation. It is normally a keyword argument to functions that I then interrogate in the function. If I'm running in testing mode, I execute the less "expensive" testing code. If I'm not in test mode, I don't. There may be better ways, but this has worked well for me. -Larry From scbauer at gmail.com Wed Nov 22 19:04:51 2006 From: scbauer at gmail.com (scbauer) Date: 22 Nov 2006 16:04:51 -0800 Subject: AVL Balancing In-Reply-To: <1164158188.787394.25990@b28g2000cwb.googlegroups.com> References: <1164154965.338691.327010@j44g2000cwa.googlegroups.com> <1164158188.787394.25990@b28g2000cwb.googlegroups.com> Message-ID: <1164240291.176865.82670@l39g2000cwd.googlegroups.com> John Machin wrote: > scba... at gmail.com wrote: > > Im working on an AVL tree > > Is this homework? Yes, this is homework. > > > that consists of balancing the tree everytime > > you add an object. > > That's a peculiar kind of AVL tree. Normally it is *not* necessary to > balance the tree every time a node is added -- it's done only if a > constraint is breached. You're right the AVL Tree shouldnt be updated everytime. > > > Im not quite grasping the concept on how to do this > > with python. > > Could you do it in any other language? No, this is an Advanced Algorithms class have to use python > > > I have seen a few topics on the web about this, and i > > clearly understand how when the balance of an AVL tree get to 2 or -2 > > you have to do a R, L, LR, or a RL rotation. Could anyone possibly help > > me/point me in the right direction as far as checking the balance and > > actually balancing the tree? Thanks in advance > class AVLTree: """Holds operations of tree""" def __init__(self): self.__root = None self.__stack=[] stack = self.__stack def addNode(self, data): """ Add node for tree""" return Node(data) def insert(self, data): if self.__root == None: self.__root = Node(data) else: current = self.__root done = False while not done: if data < current.get_data(): if current.left == None: current.left = Node(data) stack.append(current) done = True else: current = current.left else: if current.right == None: current.right = Node(data) stack.append(current) done = True else: current = current.right > Perhaps if you could show us what you have done already -- I'd be > expecting a class to represent a node, and maybe another to represent > the root of the tree -- and give us an idea of your Python proficency > level (so that we can tailor the advice accordingly), we could help > you. Basically what im trying to do is use a stack to keep track of the items in the AVL tree so that rotations will go smoothly. Having problems with the stack getting initialized and actually storing the data there. So that i can reference the elements stack[-3].left = stack[-2].right and so on for balancing. thanks scbauer From no-spam at no-spam-no-spam.invalid Thu Nov 16 10:05:55 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 16 Nov 2006 16:05:55 +0100 Subject: Multithreaded C API Python questions In-Reply-To: References: <7vCdnSqE260grc7YRVnzvQ@telenor.com> Message-ID: Svein Seldal wrote: You seem to use the functions in very rude manner - wanting to force the GIL around at lowest level. Better forget the word GIL and think about acquiring and releasing Threads. For each thread wanting to execute Python stuff there has to be a thread state (ts). And then you have to enter/leave for executing Python by using the thread state. PyEval_InitThreads enters Python (incl. the GIL) first time. To let Python free in main thread do ts=PyEval_SaveThread() // or more easy: Py_BEGIN_ALLOW_THREADS to reenter Python do simply: PyEval_RestoreThread(ts) // or: Py_END_ALLOW_THREADS Forget all the low level PyGIL... functions. when you really want another c thread to enter Python first time with no thread state existing through Python itsel (better make the thread in Python with thread.start_new ?), then you have to do once ts_cthread = PyThreadState_New(interp) then enter Python in this thread: PyEval_AcquireThread( ts_cthread ) to leave again: PyEval_ReleaseThread( ts_cthread ) If you just loop the call_py_function_send() mainly in this thread you probably better create the thread at all in Python and make the loop there. You probably stick too much to C-level at any price :-) Probably you just do a PyRun_xxxx in main thread and then everything else in Python, and expose C-parts for the thread-loop to Python as function (in other_py_inits) - where in the c-function you probably have the usual Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS bracket during time consuming/system/reenter-endangered message stuff. Robert > I think I've found the bug, but I need to confirm this behavior. > > My findings is that if you use PyEval_InitThreads(), it is crucial to > release the GIL with PyEval_ReleaseThread() afterwards. > > The API docs states that you can release the GIL with > PyEval_ReleaseLock() or PyEval_ReleaseThread() AFAICS. > http://docs.python.org/api/threads.html under docs of void > PyEval_InitThreads(). > > However, if I do use PyEval_ReleaseLock() it will crash shortly after > with "Fatal Python error: ceval: tstate mix-up" in a multithreaded C > environment. > > If I use PyEval_ReleaseThread() to release the GIL, my app seems stable. > I release the GIL like this: > > PyThreadState *pts = PyGILState_GetThisThreadState(); > PyEval_ReleaseThread(pts); > > Now, is this a feature or expected behavior in python (i.e. unclear API > documentation), or is this a bug in python itself? > > > Regards, > Svein > > > PS: > > For reference I did something like this in pseudo-code: > > Py_Initialize(); > PyEval_InitThreads(); > > other_py_inits(); // Load py modules, etc. > > PyEval_ReleaseLock(); // <-- MAKES THE APP UNSTABLE > > create_c_thread(); > > PyGILState_STATE gstate; > gstate = PyGILState_Ensure(); > > call_py_function_main(); // Py main() wont return > > PyGILState_Release(gstate); > > > And the "main" of the C thread function looks like this: > while(1) > { > PyGILState_STATE gstate; > gstate = PyGILState_Ensure(); > > call_py_function_send(); > > PyGILState_Release(gstate); > } From paul at boddie.org.uk Thu Nov 16 04:59:52 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Nov 2006 01:59:52 -0800 Subject: lxml/ElementTree and .tail References: <455C1887.6060602@web.de> Message-ID: <1163671192.876928.35960@f16g2000cwb.googlegroups.com> Stefan Behnel wrote: > [Remove an element, remove following nodes] > Yes, it is. Just look at the API. It's an attribute of an Element, isn't it? > What other API do you know where removing an element from a data structure > leaves part of the element behind? I guess it depends on what you regard an element to be... [...] > IMHO, DOM has a pretty significant mismatch with Python. ...in the DOM or otherwise: http://www.w3.org/TR/2006/REC-xml-20060816/#sec-logical-struct Paul From 120psi at gmail.com Fri Nov 24 03:11:09 2006 From: 120psi at gmail.com (120psi at gmail.com) Date: 24 Nov 2006 00:11:09 -0800 Subject: Local variables persist in functions? Message-ID: <1164355869.607182.278200@l12g2000cwl.googlegroups.com> I'm a bit baffled. Here is a bit of fairly straightforward code: def _chunkify( l, chunkSize, _curList = list() ): print _curList # yay for printf debugging if len( l ) <= chunkSize: _curList.append( l ) else: newChunk = l[:chunkSize] _curList.append( newChunk ) _chunkify( l[chunkSize:], chunkSize, _curList ) return _curList _chunkify simply breaks a sequence into a sequence of smaller lists of size <= chunkSize. The first call works fine, but if I call it multiple times, weirdness happens. chunks = _chunkify( list, size ) # _curList keeps its previous value! chunks = _chunkify( list, size, list() ) # this works as expected Considering the default value of _curList, these statements should be identical. Any pointers? Did I miss something in the python reference manual? (running 2.4.3, fyi) Thanks, Nils From st at tobiah.org Thu Nov 2 14:00:00 2006 From: st at tobiah.org (tobiah) Date: Thu, 02 Nov 2006 11:00:00 -0800 Subject: Creating db front end or middleware. Message-ID: <454a3347$0$12193$88260bb3@free.teranews.com> Let's say I want to write a new tool to do something to, or report on people in a database. Each tool is going to have to have all sorts of routines that know about the relationship between the data. The first thought is to write a library of routines that do things like, change_address(), or fire_employee() or whatever. Whoops, now we've decided to move to python. I have to write all of that again. So I thought, shouldn't there be a cloud that sits in front of the database to which I can ask these services of? Some process that awaits requests for information, or handles new incoming data. Now new apps written in any language should be able to use a basic protocol in order to get the work done. The question then, is what the best way to do this is. First I thought of using cherrypy to sit and listen to POST requests, but this would make passing complex structures extremely inconvenient. Then I thought about WSDL. Would this be the next logical step, or is this more for allowing different companies to communicate with each other when there needs to be a broadcast description of the interface? If it is to be WSDL, what is a good place to get concise information as to how to set this up? It would be written in python. Thanks, Tobiah -- Posted via a free Usenet account from http://www.teranews.com From harry.g.george at boeing.com Wed Nov 15 17:15:54 2006 From: harry.g.george at boeing.com (Harry George) Date: Wed, 15 Nov 2006 22:15:54 GMT Subject: Will GPL Java eat into Python marketshare? References: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> Message-ID: "walterbyrd" writes: > Some think it will. > > Up untill now, Java has never been standard across different versions > of Linux and Unix. Some think that is one reason that some developers > have avoided Java in favor of Python. Now that Java has been GPL'd that > might change. > > IMO: it won't make much difference. But I don't really know. > Short answer: People use Python instead of Java because people (at least intelligent people) tend to avoid pain. Long answer: Changing licenses doesn't magically change Java's architecture. It is still a closed world of reinvent-the-wheel, my-way-or-the-highway. Which is antithetical to Python's promiscuous interface-with-anything approach. -- Harry George PLM Engineering Architecture From bignose+hates-spam at benfinney.id.au Thu Nov 23 17:39:10 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 24 Nov 2006 09:39:10 +1100 Subject: sys.stderr.write and sys.exit References: <1164278785.075748.220690@j44g2000cwa.googlegroups.com> Message-ID: <87hcwpvldd.fsf@benfinney.id.au> "GinTon" writes: > Is the same use _sys.stderr.write('error message'); sys.exit(1)_ > than _sys.exit('error message')_ ? (Note: The underscore '_' is a valid character in Python code, so I was quite confused by what you wrote and had to read it several times to see that you were intending the underscores not to be part of the code. Better to show a line of code on its own line in your message.) Code that wants to catch SystemExit will get a different exception object in each case:: >>> import sys >>> from StringIO import StringIO >>> sys.stderr = StringIO() >>> try: ... sys.stderr.write('error message') ... sys.exit(1) ... except SystemExit, e: ... print "stderr contains:", sys.stderr.getvalue() ... print "e.code is:", e.code ... stderr contains: error message e.code is: 1 >>> try: ... sys.exit('error message') ... except SystemExit, e: ... print "stderr contains:", sys.stderr.getvalue() ... print "e.code is:", e.code ... stderr contains: error message e.code is: error message I quite often catch SystemExit in unit tests, or other code that is inspecting a program module. -- \ "I have a large seashell collection, which I keep scattered on | `\ the beaches all over the world. Maybe you've seen it." -- | _o__) Steven Wright | Ben Finney From johnjsal at NOSPAMgmail.com Wed Nov 8 13:21:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Nov 2006 13:21:39 -0500 Subject: is this the right way to do subclasses? Message-ID: <45522074$0$17101$c3e8da3@news.astraweb.com> Ok, back to my so-called "game." I'm just curious if I've implemented the subclasses properly, because it seems like an awful lot of repetition with the parameters. And again, if I want to add a new attribute later, I'd have to change a lot of things. I can't help but get the feeling that I'm doing something very inefficiently. Thanks! class Character(object): def __init__(self, name, strength, dexterity, intelligence): self.name = name self.health = 10 self.strength = strength self.dexterity = dexterity self.intelligence = intelligence class Fighter(Character): def __init__(self, name, strength, dexterity, intelligence): Character.__init__(self, name, strength, dexterity, intelligence) self.health += 2 self.strength += 1 class Thief(Character): def __init__(self, name, strength, dexterity, intelligence): Character.__init__(self, name, strength, dexterity, intelligence) self.health += 1 self.dexterity += 1 class Mage(Character): def __init__(self, name, strength, dexterity, intelligence): Character.__init__(self, name, strength, dexterity, intelligence) self.intelligence += 1 From nick at craig-wood.com Sat Nov 4 05:30:09 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 04 Nov 2006 04:30:09 -0600 Subject: Sorted and reversed on huge dict ? References: <1162580533.981364.211860@h54g2000cwb.googlegroups.com> <7xvelwib1b.fsf@ruckus.brouhaha.com> <1162590153.024233.311670@b28g2000cwb.googlegroups.com> <7xirhwi438.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > is there a good way to know how much ram is used directly from > > python (or should i rely on 'top' and other unix command? > > I think try resource.getrusage() That should work (under BSD anyway) but unfortunately doesn't under linux :-( >From the man page CONFORMING TO SVr4, 4.3BSD. POSIX.1-2001 specifies getrusage(), but only specifies the fields ru_utime and ru_stime. and The above struct was taken from 4.3BSD Reno. Not all fields are mean- ingful under Linux. In linux 2.4 only the fields ru_utime, ru_stime, ru_minflt, and ru_majflt are maintained. Since Linux 2.6, ru_nvcsw and ru_nivcsw are also maintained. Ie none of the memory based ones are filled in. This linux only code works though :- def memory_used(): """Return the memory used by this process under linux in bytes""" return int(file("/proc/self/statm").read().split()[0]) * resource.getpagesize() Eg >>> import resource >>> def memory_used(): ... return int(file("/proc/self/statm").read().split()[0]) * resource.getpagesize() ... >>> print memory_used() 4575232 >>> a=10000000*"x" >>> print memory_used() 14577664 >>> If anyone knows a (unix) portable way of doing this I'd be interested! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From rtw at freenet.co.uk Mon Nov 27 15:26:11 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 27 Nov 2006 14:26:11 -0600 Subject: super() and type() References: Message-ID: Chris Mellon wrote in news:mailman.777.1164653627.32031.python-list at python.org in comp.lang.python: > I see super documented, and in use, as below (from the Python > documentation) > > class C(B): > def meth(self, arg): > super(C, self).meth(arg) > > I'd like to not write C all the time, so is there any problem with > writing: > > class C(B): > def meth(self, arg): > super(type(self), self).meth(arg) > > > This seems to work in practice but I don't see it used anywhere and > I'm worried what I might be missing. Have you considered what happens if somebody writes: class D(C): def meth(self, arg): super( D, self ).meth( arg ) > > This was especially brought to my attention because pylint flags the > second usage as invalid, and I'm not sure if it should be considered a > false positive or not. Nope, the type argument to super tells it where you are in the type hierarchy, type(self) is always the top of the hierarchy. Rob. -- http://www.victim-prime.dsl.pipex.com/ From fredrik at pythonware.com Wed Nov 29 02:18:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Nov 2006 08:18:21 +0100 Subject: Python program that validates an url against w3c markup validator In-Reply-To: References: <1164778181.910135.53070@j44g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > >>> f = urllib.urlopen("http://validator.w3.org/check?uri=" + uri) > >>> print f.headers here's the specification, btw: http://validator.w3.org/docs/api.html From fd0man at gmail.com Sat Nov 11 20:23:24 2006 From: fd0man at gmail.com (Michael B. Trausch) Date: Sat, 11 Nov 2006 20:23:24 -0500 Subject: Decimal() instead of float? Message-ID: <1163294604.4675.4.camel@pepper> Is there a way to use Decimal() by default in Python instead of float? I've no use for the float type, and I have some stuff that would require Decimal(), but it is kind of a pain to try and cast things all over the place all the time. Float is just way too inexact for me. I am searching around, and I don't see anything helpful, but I could (as always) be missing something... I tried (rather na?vely) to just do something like: >>> import decimal >>> float=Decimal >>> x=1.1 >>> x 1.1000000000000001 >>> But, that didn't work (obviously). It was a shot, anyway. Are there any ideas, or does anyone have a way around this? I would prefer to not have to convert incoming floating point numbers to strings and then convert them to Decimal() types every single time that I want to use them (which would be in *every* case). For example, I have a ZIP code database that can do some processing on its numbers, and the numbers are stored as floating point values (exactly) but Python doesn't get them right; so the Decimal() thing would be needed. *shrugs* Thanks a bunch, Mike -- Michael B. Trausch fd0man at gmail.com Phone: (404) 592-5746 Jabber IM: fd0man at livejournal.com Demand Freedom! Use open and free protocols, standards, and software! -------------- next part -------------- An HTML attachment was scrubbed... URL: From no-spam at no-spam-no-spam.invalid Thu Nov 9 14:11:29 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 09 Nov 2006 20:11:29 +0100 Subject: Multithreaded C API Python questions In-Reply-To: <7vCdnSqE260grc7YRVnzvQ@telenor.com> References: <7vCdnSqE260grc7YRVnzvQ@telenor.com> Message-ID: Svein Seldal wrote: > robert wrote: >> PyGILState_Ensure/Release guarantees to establish the GIL - even if it >> was already held (useful if you deal with complex call >> ordering/dependencies) > > I understand this to mean that I dont need to explicitly lock the GIL > (with PyEval_AcquireLock() or PyEval_AcquireThread()). > > Well I cant figure out the PyGILState_Ensure() because if I only use > this function to establish the GIL, when calling python, python will > shortly after crash with "Fatal Python error: ceval: tstate mix-up". > This happens consistently when the main app and the extra thread has > called python and both are busy executing python code. Do did't tell enough to see what you want to do on the big picture. usually you create a thread through Python. If you boot Python at all from C you have to do PyEval_InitThreads or maybe more simple use the high level layer PyRun_... If you boot a new Python thread manually or a separated interpreter (with separated module state) from outside the you have to also do: (PyInterpreterState* PyInterpreterState_New() ) PyThreadState* PyThreadState_New( PyInterpreterState *interp) void PyEval_AcquireThread( PyThreadState *tstate) If you are already in a Python thread but don't for some reason not know the current thread state: PyThreadState* PyThreadState_Get( ) but usually you release with PyThreadState* PyEval_SaveThread( ) / Py_BEGIN_ALLOW_THREADS >> PyObject_CallObject(...) calls Python code. Thus the interpreter >> will switch and do as usuall during that. > > BTW What do you mean by switch? the automatic scheduling every sys.getcheckinterval() etc.. you mentioned You'd only have to take care for that, if your C-code does things (e.g. calling python basic funcs) for a long time and doesn't release the lock with Py_BEGIN_ALLOW_THREADS ... > The main problem is that not done this way, it's the other way around. > My main C app will call a python function which will be a lengthy time > consuming process. > > The main C app will call python and it will never return from > PyObject_CallObject(...), while the extra thread should call a py > function to deliver occational messages into C. Maybe simply boot Python in the main thread (Py_Initialize( )) and run off Python possibly as simple as PyRun_String and let Python do thread.start_new(...) You'd not have to worry much about states. ( and later you'd probably even more simple do "python myapp.py" and expose your C app as extension module :-) ) -robert From steve at REMOVE.THIS.cybersource.com.au Thu Nov 16 17:27:12 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 17 Nov 2006 09:27:12 +1100 Subject: Question about unreasonable slowness References: <1163709918.739398.194880@b28g2000cwb.googlegroups.com> Message-ID: On Thu, 16 Nov 2006 12:45:18 -0800, allenjo5 wrote: > [ Warning: I'm new to Python. Don't know it at all really yet, but had > to examine some 3rd party code because of performance problems with it. > ] > > Here's a code snippet: > > i = 0 > while (i < 20): > i = i + 1 You probably want to change that to: for i in range(20): If 20 is just a place-holder, and the real value is much bigger, change the range() to xrange(). > (shellIn, shellOut) = os.popen4("/bin/sh -c ':'") # for testing, the > spawned shell does nothing > print 'next' > # for line in shellOut: > # print line > > On my system (AIX 5.1 if it matters, with Python 2.4.3), this simple > loop spawning 20 subshells takes .75 sec. Ok, that's reasonable. Now, > if I uncomment the two commented lines, which loop over the empty > shellOut array, the progam now takes 11 secs. That slowdown seems > very hard to believe. Why should it slow down so much? What are you using to time the code? Replacing print statements with "pass", I get these results: >>> import timeit >>> >>> def test(): ... i = 0 ... while (i < 20): ... i = i + 1 ... (shellIn, shellOut) = os.popen4("/bin/sh -c ':'") ... pass # print 'next' ... for line in shellOut: ... pass # print line ... >>> timeit.Timer("test()", "from __main__ import test\nimport os").timeit(1) 0.49781703948974609 >>> timeit.Timer("test()", "from __main__ import test\nimport os").timeit(100) 54.894074201583862 About 0.5 second to open and dispose of 20 subshells, even with the "for line in shellOut" loop. I think you need some more fine-grained testing to determine whether the slowdown is actually happening inside the "for line in shellOut" loop or inside the while loop or when the while loop completes. -- Steven. From robert.kern at gmail.com Thu Nov 2 16:00:51 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 02 Nov 2006 13:00:51 -0800 Subject: Python in sci/tech applications In-Reply-To: References: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> <1162489638.013433.102180@h48g2000cwc.googlegroups.com> <1162491753.605134.162700@i42g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > Robert Kern wrote: >> bearophileHUGS at lycos.com wrote: >> >>> Robert Kern: >>> >>>> We distribute mingw set up to do this with our "Enthought >>>> Edition" Python distribution. >>>> http://code.enthought.com/enthon/ >>> Sorry, maybe I'm blind but I don't see MinGW listed in that page... >>> Maybe it's included but not listed... >> >> It's there. >> > Well I tend to believe you, but Firefox is calling you a liar: a search > fails at "min". Sorry, by "it's there" I meant "it is actually included in the distribution regardless of any omissions on the web page." > Do you anticipate a 2.5-based release any time soon? We'll start working on it soon, at least. -- 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 pavlovevidence at gmail.com Thu Nov 23 20:08:03 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 23 Nov 2006 17:08:03 -0800 Subject: Trying to understand Python objects In-Reply-To: References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> Message-ID: <1164330483.262739.154280@k70g2000cwa.googlegroups.com> Aahz wrote: > In article , > Ben Finney wrote: > > > >Typically, classes are created as a subclass of another class. The > >top-level basic type in Python is 'object', so if your class doesn't > >make sense deriving from anything else, derive from 'object'. > > > > class Point(object): > > pass > > > >Defining a class with *no* superclass is not recommended. If you don't > >yet understand the difference between the above style (called a > >"new-style" class) and the style you presented, you should always > >derive from a superclass ('object' or something more specific) until > >you encounter a situation where that causes a problem. > > Side note: I disagree with the above advice, but it's Thanksgiving and I > don't have enough room on the margin for the proof. I think classic > classes are just fine. Absolutely. We don't want newbies' feeble brains to explode. Carl Banks From martin.witte at gmail.com Wed Nov 1 14:56:50 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 1 Nov 2006 11:56:50 -0800 Subject: best way to check if a file exists? In-Reply-To: References: <1162383348.925961.231160@h48g2000cwc.googlegroups.com> <1162390455.727684.118970@b28g2000cwb.googlegroups.com> Message-ID: <1162411010.495259.311680@i42g2000cwa.googlegroups.com> On Nov 1, 3:44 pm, Ben Finney wrote: > "witte... at hotmail.com" writes: > > Ben Finney wrote: > > > "witte... at hotmail.com" writes: > > > > You could try to read the file, if that fails it doesn't exist: > > > > Except that there are other conditions than "File doesn't exist" > > > that can cause an 'open' to fail. > > > Ok, true. You can test explicit on non existence as follows, and then > > decide to open the fileOr you can simply use 'os.path.exists', as has been suggested several > times in this thread. > os.path.exists() checks if a path exists, so a directory as argument also returns True > -- > \ "The way to build large Python applications is to componentize | > `\ and loosely-couple the hell out of everything." -- Aahz | > _o__) | > Ben Finney From pavlovevidence at gmail.com Fri Nov 3 18:24:27 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 3 Nov 2006 15:24:27 -0800 Subject: Javascript is turning into Python?! In-Reply-To: <7xslh1dmgt.fsf_-_@ruckus.brouhaha.com> References: <7xslh1dmgt.fsf_-_@ruckus.brouhaha.com> Message-ID: <1162596267.518634.164170@h54g2000cwb.googlegroups.com> Paul Rubin wrote: > I hadn't seem this before. New Javascript 1.7 features: > > - Generators > - Iterators > - Array comprehensions > - Destructuring assignment > > Sounds like another language we know. > > http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7 Maybe in exchange, Python can borrow the let statement. Carl Banks From fredrik at pythonware.com Mon Nov 13 15:58:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Nov 2006 21:58:50 +0100 Subject: str.title question after ' In-Reply-To: <1163417015.047332.197000@m73g2000cwd.googlegroups.com> References: <1163417015.047332.197000@m73g2000cwd.googlegroups.com> Message-ID: Leo Kislov wrote: >> Is there an easy way to get what I want? > > def title_words(s): > words = re.split('(\s+)', s) > return ''.join(word[0:1].upper()+word[1:] for word in words) nit: to work well also for Unicode strings using arbitrary alphabets, you should use title() instead of upper(). a naive upper() will do the wrong thing in some cases, as can be seen in the following example: >>> u = u"\u01C9" >>> unicodedata.name(u) 'LATIN SMALL LETTER LJ' >>> unicodedata.name(u.upper()) 'LATIN CAPITAL LETTER LJ' >>> unicodedata.name(u.title()) 'LATIN CAPITAL LETTER L WITH SMALL LETTER J' From sjmachin at lexicon.net Sat Nov 18 17:38:20 2006 From: sjmachin at lexicon.net (John Machin) Date: 18 Nov 2006 14:38:20 -0800 Subject: print with variable justification (with *) References: <1163883589.401180.271190@m73g2000cwd.googlegroups.com> Message-ID: <1163889500.346015.214830@m73g2000cwd.googlegroups.com> tom wrote: > Why Tea wrote: > > print format % values > > An optional minimum width of the conversion, specified using one or > > more digits or an asterisk (*), which means that the width is taken > > from the next item in values > > > > That's from one of O'reilly's books. But there is no example and I > > couldn't get it to work by trials and errors. Does anyone have a > > working example? > > > > /Why Tea > > > > > value = 3.141592654 > print "%1.3f" % value Please consider reading the subject of a message occasionally :) | >>> value = 3.141592654 | >>> print "%1.3f" % value | 3.142 | >>> print "%10.3f" % value | 3.142 | >>> print "%*.3f" % (1, value) | 3.142 | >>> print "%*.3f" % (10, value) | 3.142 | >>> for n in range(11): | ... print "%*.3f" % (n, value) | ... | 3.142 | 3.142 | 3.142 | 3.142 | 3.142 | 3.142 | 3.142 | 3.142 | 3.142 | 3.142 | 3.142 | >>> > > > there you go :) There *you* go :) > look at printf in c for general ideas about the format > specifiers Unfortunately this is about the same advice as given by the official Python tutorial: """Most formats work exactly as in C [snip] Using * to pass the width or precision in as a separate (integer) argument is supported""" Not quite so many folks come to Python with a background in C these days. Is anyone aware of a tutorial that covers % formatting from a standing start? Cheers, John From fredrik at pythonware.com Mon Nov 20 03:57:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Nov 2006 09:57:36 +0100 Subject: a few extensions for the itertools In-Reply-To: <45616b46$0$12642$3b214f66@tunews.univie.ac.at> References: <4560bfb0$0$10578$3b214f66@tunews.univie.ac.at> <45616b46$0$12642$3b214f66@tunews.univie.ac.at> Message-ID: Mathias Panzenboeck wrote: > No, because the builtin sum want's a list. the one in Python doesn't: >>> def g(): ... for i in range(3): ... print "yield", i ... yield i ... >>> sum(g()) yield 0 yield 1 yield 2 3 From ompaniess at gmail.com Fri Nov 3 10:03:10 2006 From: ompaniess at gmail.com (ompaniess) Date: 3 Nov 2006 07:03:10 -0800 Subject: MemoDepot: build YOUR OWN online notes library - anything, anytime, anywhere Message-ID: <1162566190.152198.250310@h48g2000cwc.googlegroups.com> Just like everybody else nowadays, you are facing infinite amount of information everyday. how can you keep those that truly matters to you? MemoDepot allows you to do just that, and much more! - Capture any information, store as notes in your MemoDepot account, and access from anywhere - Organize your notes the way you like, they are always available at your fingertips - Pinpoint any notes by powerful search, just when you need it - Share your notes with others - Export your notes to local machine, so you take control, not MemoDepot With MemoDepot, you no longer have to throw away any useful information: contacts, ideas, experience, coupons, receipts, pictures, web pages, hard Googled-out results, programming sample codes, teacher's handout, scientific references, or simply favored book passages...... yes, ANYTHING. It is the place to deposit your knowledge; it is the way to extend your memory. MemoDepot is NOT merely a storage solution, a screen scraper, NOR is another online notebook, search engine or editor - it is an end to end knowledge build and management system, everyday, in the most convenient way. To truly appreciate why MemoDepot tool and service are so powerful, take a few minutes to check out: http://www.memodepot.com/noteserver/flashes/memodepot.pps (PowerPonit) http://www.memodepot.com/noteserver/flashes/memodepot_demo.html (Flash Demo) http://www.memodepot.com (Get started!) Any comments or suggestions, send to: support at memodepot.com From edgomez at consultant.com Mon Nov 27 12:44:46 2006 From: edgomez at consultant.com (Edwin Gomez) Date: Mon, 27 Nov 2006 12:44:46 -0500 Subject: Calling a thread asynchronously with a callback Message-ID: <20061127174454.4407383986@ws1-2a.us4.outblaze.com> I'm a C# developer and I'm new to Python. I would like to know if the concept of Asynchronous call-backs exists in Python. Basically what I mean is that I dispatch a thread and when the thread completes it invokes a method from the calling thread. Sort event driven concept with threads. Thanks. Ed Gomez From eric_brunel at despammed.com Thu Nov 9 03:14:10 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 09 Nov 2006 09:14:10 +0100 Subject: Problem getting a file pathname with tkFileDialog References: <1163012468.055428.124690@h48g2000cwc.googlegroups.com> Message-ID: On Wed, 08 Nov 2006 20:01:08 +0100, wrote: > Hello, > I am working on a school project that requires me to get the path of a > filename for future treatment. > I've tried getting a file with tkFileDialog.askopenfile. > > > ******************************************** > import tkFileDialog > file = tkFileDialog.askopenfile() > print file > ******************************************** > > > It prints the opened files stuff, but I just can not find how to get > that path as a string. I've searched around google and the present > group, and found no documentation on the file class used with > tkFileDialog. Does someone have a solution for that? Use tkFileDialog.askopenfilename? HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From ptmcg at austin.rr._bogus_.com Wed Nov 1 12:03:10 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 01 Nov 2006 17:03:10 GMT Subject: Style for modules with lots of constants References: Message-ID: "Paul McGuire" wrote in message news:XU32h.436$lx6.417 at tornado.texas.rr.com... Errata: > opAssoc = Constants(object) Urk! Should be "opAssoc = Constants()" > and so on. In the client modules they would simply enter "from glk import > fileusage, filemode". Or if they just "import glk", the references to the > constants look like "glk.filemode.Append", "flk.fileusage.TextMode", etc., Should be "glk.fileusage.TextMode". -- Paul From no-spam at no-spam-no-spam.invalid Fri Nov 3 05:48:54 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 03 Nov 2006 11:48:54 +0100 Subject: Feature Request: Py_NewInterpreter to create separate GIL (branch) In-Reply-To: References: Message-ID: Feature Request: Py_NewInterpreter to create separate GIL (branch) Daniel Dittmar wrote: > robert wrote: >> I'd like to use multiple CPU cores for selected time consuming Python >> computations (incl. numpy/scipy) in a frictionless manner. >> >> Interprocess communication is tedious and out of question, so I >> thought about simply using a more Python interpreter instances >> (Py_NewInterpreter) with extra GIL in the same process. > > If I understand Python/ceval.c, the GIL is really global, not specific > to an interpreter instance: > static PyThread_type_lock interpreter_lock = 0; /* This is the GIL */ > Thats the show stopper as of now. There are only a handfull funcs in ceval.c to use that very global lock. The rest uses that funcs around thread states. Would it be a possibilty in next Python to have the lock separate for each Interpreter instance. Thus: have *interpreter_lock separate in each PyThreadState instance and only threads of same Interpreter have same GIL? Separation between Interpreters seems to be enough. The Interpreter runs mainly on the stack. Possibly only very few global C-level resources would require individual extra locks. Sooner or later Python will have to answer the multi-processor question. A per-interpreter GIL and a nice module for tunneling Python-Objects directly between Interpreters inside one process might be the answer at the right border-line ? Existing extension code base would remain compatible, as far as there is already decent locking on module globals, which is the the usual case. Robert From cemerick at snowtide.com Sat Nov 18 21:56:10 2006 From: cemerick at snowtide.com (Chas Emerick) Date: Sat, 18 Nov 2006 21:56:10 -0500 Subject: lxml/ElementTree and .tail In-Reply-To: References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> <761846B7-E374-41FE-8804-CBB3D42FD4D2@snowtide.com> <1163835505.102190.140060@b28g2000cwb.googlegroups.com> <894503B9-B571-42E3-9FA0-B0C67D333A3D@snowtide.com> Message-ID: <04CD655B-63BA-4902-B4A6-53F5B787C108@snowtide.com> On Nov 18, 2006, at 1:12 PM, Fredrik Lundh wrote: > Chas Emerick wrote: > >> Further, the fact that ET/lxml works the way that it does makes me >> think that there may be some other landmines in the underlying model >> that we might not have discovered until some days, weeks, etc., had >> passed > > so the real reason you posted your original post was to spread some > FUD, > not to get help? that's a bit disappointing. Yeah, that's exactly it. In fact, if you look back at the head of this thread, you'll see how I was looking to disparage ET. I especially wanted to make sure ET's API doesn't get any traction in the python community. It's especially important that ET not find popular success and acclaim -- I'd have quite a bit to gain from it remaining a niche library. Fredrik, I wasn't attempting to spread anything. I was confused, I posed some illustrative examples, and asked for people's thoughts. Your reply gave me the right vocabulary to find more information (i.e. about Infoset), and I replied with a overview of what I had learned so as to benefit anyone with similar questions or confusion in the future. A discussion ensued. ET (and lxml) is obviously extremely successful, widely used, and for good reason. It's just not right for us, but you incorrectly surmised that I was simply lazy by not modifying/extending ET/lxml to make it suitable for our purposes even when other libraries existed that better meshed with our requirements. I tried to answer as straightforwardly as possible, and (regrettably, it turns out) included the fact that I had worried that our apparent conceptual differences indicated that we might find other instances where ET/ lxml works differently than we would expect. I think that's very rational, and doesn't speak poorly of ET in any way (especially given its obvious success elsewhere). - Chas From bignose+hates-spam at benfinney.id.au Wed Nov 1 09:00:53 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 02 Nov 2006 01:00:53 +1100 Subject: best way to check if a file exists? References: <1162383348.925961.231160@h48g2000cwc.googlegroups.com> Message-ID: <87ac3b5kru.fsf@benfinney.id.au> "wittempj at hotmail.com" writes: > You could try to read the file, if that fails it doesn't exist: > > try: > f = open('xxx') > except IOError: > f = open('xxx', 'w') > print "file doesn't exist" > print f Except that there are other conditions than "File doesn't exist" that can cause an 'open' to fail. -- \ "If you continue running Windows, your system may become | `\ unstable." -- Microsoft, Windows 95 BSOD message | _o__) | Ben Finney From mnations at gmail.com Sun Nov 5 01:28:02 2006 From: mnations at gmail.com (Mudcat) Date: 4 Nov 2006 22:28:02 -0800 Subject: python GUIs comparison (want) In-Reply-To: <454d73ab@quokka.wn.com.au> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <1162657420.655675.185930@e3g2000cwe.googlegroups.com> <454d73ab@quokka.wn.com.au> Message-ID: <1162708081.974808.283370@i42g2000cwa.googlegroups.com> When you say far better widgets, do you mean that it has a greater number of widgets to choose from, or that the types of widgets are basically the same but have a greater amount of flexibility in them? Personally I find programming in Tkinter fairly simple and straight-forward. I'm sure a lot of that is due to the fact I've been using it for a while and have many templates already available when I start to work on something new. But I don't find myself questioning it very much for unnecessary typing like I do other things. As far as appearance goes, I've scoured the net looking for examples of widgets produced wxPython or other UIs, and I really don't see that much difference than Tkinter. Now I haven't done a whole lot of programming on XP, but as far as W2000 is concerned they all look very similar. What would be really cool is if someone were to come up with a UI that has a totally new look and feel than anything that currently exists on Windows. It seems like most of the native look and feel, even in XP, are rather boxy and stale. I don't like Macs, but they do have cool looking windows and frames. Now I hardly know anything at all about low-level windows calls and what is/is not possible. But I know that many applications draw their own windows, skins, and functionality widgets to provide a sharper appearance. It seems like it would be possible for someone to draw these widgets and provide an api to display them through Python. timmy wrote: > Mudcat wrote: > > I have been using Tkinter for several years now. Recently I have been > > thinking about switching to something else that may have a sharper > > appearance. However I'm not sure what that may be, and if that > > something else is *that* much better than what I'm already using. > > > > Does everyone agree that wxPython looks best on Windows? I've also read > > in a couple of places where Dabo looks pretty good as well. > > > > So if someone were to pick a UI that gave the best appearance, what > > would they choose? > > > > > i've been using wxpython for a few years and it's great. > it's got far better widgets then tkinter and it's speed is greater on > large stuff as well. > it's got a great support forum and the maintainer robin dunn does a > great job of answering all questions. > i can't particularly fault wxpython. it looks great on all platforms and > maintain the native look and feel of the platofrm as well. From no-spam at no-spam-no-spam.invalid Sat Nov 18 07:44:12 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sat, 18 Nov 2006 13:44:12 +0100 Subject: numpy magic: cast scalar returns auto to python types float & int ? In-Reply-To: References: Message-ID: Robert Kern wrote: > robert wrote: > >> Didn't find the relevant reasoning within time. Yet guess the reason is isolated-module-centric. > > I gave you a brief rundown on this list already. > > http://mail.python.org/pipermail/python-list/2006-October/411145.html think I took this into account already for this discussion. >>> array([1.,.0,4,4,],float32) array([ 1., 0., 4., 4.], dtype=float32) >>> a=_ >>> a+3 array([ 4., 3., 7., 7.], dtype=float32) >>> a+3.0 array([ 4., 3., 7., 7.], dtype=float32) >>> 3+a array([ 4., 3., 7., 7.], dtype=float32) >>> 3.0+a array([ 4., 3., 7., 7.], dtype=float32) >>> 3.0*a array([ 3., 0., 12., 12.], dtype=float32) numpy does anyway not force the precision upwards for float32 x python-float. ( what is good so). There remains the argument, that (float64,int32) scalars coming out should - by default - support the array interface. How many people are there to expect and use this? I'd have never noticed it, if it wouldn't have been mentioned here. Have never seen such code nor seen somewhere or felt myself such a requirement. Thats very special an maybe can be turned on by a global option - if there is more than a handful of users for that. I still think this is over-design and that it brings much much more disadvantages than advantages to let these beasts out by default into a general purpose language like python. The target area for numpy output is much bigger than that e.g. for matlab script someone uses in a rush to create a paper. Maybe for users who want to make an alt-matlab-only box out of python there could be a global switch somewhere or a enforcing versions of the data types ... Seeing the speed impact and pickle-problems now everywere on post-computations upon numpy out, its a critical decision to migrate code to numpy. Almost a killer. Even if I spread float()-casts everywhere, this cost a lot of speed, makes code ugly etc., and its an holey sieve. I think I'll stay as a voice to vote heavily against that scheme of numpy scalar types. 11 on a scale from 0 to 10 :-) > And yet again, the best place for numpy questions is the numpy mailing list, not > here. Here, you will get maybe one or two people responding to you, usually me, > and I'm a cranky SOB. There you will get much nicer people answering your > questions and more fully. > > http://www.scipy.org/Mailing_Lists Maybe once I take the hurdle to use this. Access and searching on such lists is somewhat proprietry. Numerics is a major field in Python land. There are also lots of cross relations to other libs and techniques. Maybe there could be a nntp-comfortable comp.lang.python.numeric for users - and also a comp.lang.python.net, comp.lang.python.ui. I think that would greatly strentghen Pythons "marketing" in the numerics domain. main clp's posting frequency is too high anyway meanwhile. Robert From onurb at xiludom.gro Fri Nov 10 05:01:49 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 10 Nov 2006 11:01:49 +0100 Subject: how is python not the same as java? In-Reply-To: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> Message-ID: <45544e0f$0$3977$426a74cc@news.free.fr> gavino wrote: > both are interpreted oo langauges...... Being "interpreted" or whatever is a feature of an *implementation*, not of a language. FWIW, CPython (the reference implementation) is compiled to byte-code, that is then executed by a virtual machine. And Sun's Java implementation works the same. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mpraveenreddy at gmail.com Sun Nov 5 13:41:16 2006 From: mpraveenreddy at gmail.com (Praveen) Date: 5 Nov 2006 10:41:16 -0800 Subject: How to get/read Hard disk label / drive label Message-ID: <1162752076.121514.313750@h48g2000cwc.googlegroups.com> I want to read individual disk label for Hard disk (C: drive, D: drive disk label) and CD-ROM disk label Please provide some pointer to the code or document. Thanks in advance. From robert.kern at gmail.com Tue Nov 7 15:19:32 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 07 Nov 2006 14:19:32 -0600 Subject: C wrapper In-Reply-To: <1162930226.658619.79830@m73g2000cwd.googlegroups.com> References: <1162928252.643092.23350@h48g2000cwc.googlegroups.com> <1162930226.658619.79830@m73g2000cwd.googlegroups.com> Message-ID: Sheldon wrote: > This function is there and is called init_mymodule() but I have other > functions that are not static. Is the module's name "_mymodule"? Or is it "mymodule"? -- 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 mail at microcorp.co.za Thu Nov 16 01:43:46 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 16 Nov 2006 08:43:46 +0200 Subject: Secure Python References: <1163646179.11586.60.camel@pc7.dolda2000.com> Message-ID: <017e01c7094b$86c36ce0$03000080@hendrik> "Fredrik Tolf" wrote: > I was thinking that maybe it could be possible to load and run untrusted > Python code, simply by loading it in a module with a modified version of > __builtins__. Without any reachable function that do unsafe operations, > code running from there shouldn't be able to do evil things. google for "sandbox" - Hendrik From claird at lairds.us Fri Nov 10 18:11:53 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 10 Nov 2006 23:11:53 +0000 Subject: PDF to text script References: <1163188222.330683.9160@e3g2000cwe.googlegroups.com> Message-ID: In article <1163188222.330683.9160 at e3g2000cwe.googlegroups.com>, Vyz wrote: >I am looking for a PDF to text script. I am working with multibyte >language PDFs on Windows Xp. I need to batch convert them to text and >feed into an encoding converter program > >Thanks for any help in this regard > From fredrik at pythonware.com Sun Nov 26 15:41:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 26 Nov 2006 21:41:03 +0100 Subject: pdb question In-Reply-To: <1164572933.131055.43940@14g2000cws.googlegroups.com> References: <1164572933.131055.43940@14g2000cws.googlegroups.com> Message-ID: tac-tics wrote: > In the Python debugger (pdb), how do you designate breakpoints at the > start of methods? > I've tried: > break methodName > break class.methodName > break object.methodName > > but none of these seem to work. What is the trick? define "seem to work". the "className.methodName" and "object.methodName" forms seem to work just fine to me (assuming that the class or object has been defined, of course). if nothing else works, you can use the line or file:line syntax. From Leo.Kislov at gmail.com Tue Nov 28 11:19:21 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 28 Nov 2006 08:19:21 -0800 Subject: Problem with imaplib (weird result if mailbox contains a %) References: Message-ID: <1164727244.400677.36150@l12g2000cwl.googlegroups.com> Antoon Pardon wrote: > This little program gives IMO a strange result. > > import imaplib > > user = "cpapen" > > cyr = imaplib.IMAP4("imap.vub.ac.be") > cyr.login("cyrus", "cOn-A1r") > rc, lst = cyr.list('""', "user/%s/*" % user) > for el in lst: > print "%r" % (el,) > > And the result is: > > '(\\HasNoChildren) "/" "user/cpapen/Out"' > '(\\HasNoChildren) "/" "user/cpapen/Punten"' > '(\\HasNoChildren) "/" "user/cpapen/Spam"' > '(\\HasNoChildren) "/" "user/cpapen/agoog to be"' > '(\\HasNoChildren) "/" "user/cpapen/artistiek &- kunst"' > '(\\HasNoChildren) "/" "user/cpapen/copains et copinnes =x="' > '(\\HasNoChildren) "/" "user/cpapen/cp &- writing"' > '(\\HasNoChildren) "/" "user/cpapen/examen"' > '(\\HasNoChildren) "/" "user/cpapen/important info (pass)"' > '(\\HasNoChildren) "/" "user/cpapen/lesmateriaal"' > '(\\HasNoChildren) "/" "user/cpapen/love &- flesh for fantasy"' > '(\\HasNoChildren) "/" "user/cpapen/media"' > '(\\HasNoChildren) "/" "user/cpapen/music &- beats"' > ('(\\HasNoChildren) "/" {25}', 'user/cpapen/newsletters %') > '' > '(\\HasNoChildren) "/" "user/cpapen/organisatie &- structuur"' > '(\\HasNoChildren) "/" "user/cpapen/sociale wetenschappen"' > '(\\HasNoChildren) "/" "user/cpapen/the closest ones to me [x]"' > '(\\HasNoChildren) "/" "user/cpapen/vubrations"' > '(\\HasNoChildren) "/" "user/cpapen/wm2addressbook"' > '(\\HasNoChildren) "/" "user/cpapen/wm2prefs"' > '(\\HasNoChildren) "/" "user/cpapen/wm2signature"' > > > What I have a problem with is the 14th and 15th line. > All other entries are strings but the 14th is a tuple. > and the 15th is an empty string. As far as I can tell > every time a "%" is in the mailbox name I get this kind of > result. > > I'm using python 2.3.3 and the imap sytem is Cyrus. > > Can someone explain what is going one? > > Is this a bug? Empty string seems to be a bug. But tuple is by design, read the docs and imap rfc. The protocol is convoluted in the first place, and so is python interface. > If it is, is it fixed in later versions? Why don't you try to pull imaplib.py from later versions? I don't think it changed that much so it should be compatible with python 2.3 > Whether or not it is a bug, can I rely on the mailbox > being the last item in the tuple in these cases? Yes (at least for list command) -- Leo From sjmachin at lexicon.net Tue Nov 21 01:33:56 2006 From: sjmachin at lexicon.net (John Machin) Date: 20 Nov 2006 22:33:56 -0800 Subject: rpncalc-2.5 RPN Calculator for Python In-Reply-To: References: <1164009539.310173.248620@m7g2000cwm.googlegroups.com> Message-ID: <1164090836.703397.45350@k70g2000cwa.googlegroups.com> Hendrik van Rooyen wrote: > "John Machin" WROTE: > > > Hendrik van Rooyen wrote: > > > "Raymond L. Buvel" wrote: > > > > > > > > > > The rpncalc package adds an interactive Reverse Polish Notation (RPN) > > > > > > Can anyone remember who the Pole was and how his name is spelled? > > > > > > (no fair googling) > > > > Remember who: yes > > Remember spelling: you must be joking; however I do remember that the > > name is given in Knuth TAOCP vol 3 as a test case for the soundex > > algorithm. > > > > name = u"\u0141ukasiewicz" # Python syntax so we're not completely OT > > :-) > > > > The first letter is LATIN CAPITAL LETTER L WITH STROKE. > > Thanks - I find it disgusting that I am completely unable to remember this - > > If his name had been Smith or Jones it would be no problem, > but just because there are a few too many consonants for me > to handle, it is as if there is a total black hole... > > A *few* too many? By my count it's 6 consonants compared with 5 in "van Rooyen". From paddy3118 at netscape.net Thu Nov 9 22:14:15 2006 From: paddy3118 at netscape.net (Paddy) Date: 9 Nov 2006 19:14:15 -0800 Subject: how is python not the same as java? References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> Message-ID: <1163128455.352864.26300@b28g2000cwb.googlegroups.com> gavino wrote: > both are interpreted oo langauges...... One can curl; the other, one can suck! (Its early, I'm sure this will not be as funny at more decent hours). Gavino, I suggest you take a very small problem, something like computing pascals triangle for example, and write implementations in both languages yourself. - Paddy. From rpdooling at gmail.com Wed Nov 8 10:53:35 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 8 Nov 2006 07:53:35 -0800 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: <4551FA0F.4000202@hotmail.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> <4551FA0F.4000202@hotmail.com> Message-ID: <1163001215.177739.238130@k70g2000cwa.googlegroups.com> Chaz Ginger wrote: >> it is supposed to be about PYTHON. Get it? I agree. And Python is an extremely serious matter calling for decorum and propriety. Don't say fuck, ni, peng, or ni-wom. http://en.wikipedia.org/wiki/Knights_who_say_Ni rd From bignose+hates-spam at benfinney.id.au Tue Nov 28 17:44:59 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 29 Nov 2006 09:44:59 +1100 Subject: ANN: CherryPy 3.0 RC1 In-Reply-To: (Christian Wyglendowski's message of "Tue, 28 Nov 2006 09:08:49 -0500") References: Message-ID: <87bqmrry1g.fsf@benfinney.id.au> "Christian Wyglendowski" writes: > I'm happy to announce the first release candidate for CherryPy 3.0. Congratulations, I'm glad to see an announcement for CherryPy. Please, in future, don't send HTML message bodies to public forums; plain text is far better for such a wide audience. -- \ "When you go in for a job interview, I think a good thing to | `\ ask is if they ever press charges." -- Jack Handey | _o__) | Ben Finney From mealier_brice at NO_SPAM_yahoo.fr Sun Nov 5 12:32:39 2006 From: mealier_brice at NO_SPAM_yahoo.fr (Brice) Date: Sun, 5 Nov 2006 18:32:39 +0100 Subject: Wait for a system command executed in the background Message-ID: <454e2037$0$97241$892e7fe2@authen.yellow.readfreenews.net> Hello I am new to python and I am really a bad programmer... As a linux user, I use quodlibet for listening to music. Quodlibet allows me to write plugins in python. I am trying to write a plugins to burn a playlist by using cdrecord, and this either in dao or tao mode. The basic of this plugin is the following: - make a temp directory - convert the songs in my playlist into wave files in the temp directory using mplayer and renaming them with 3 digits number so that the order of my playlist is conserved - normalize the wave files - burn the cd - delete the temp directory. At the time, I have a working solution (not fully developped by myself...), but in this solution os.system is used to start the different shell commands and the commands do not have a & at the end. Therefore during the whole execution of the plugin, quodlibet is not responsive. What I would like to is program the whole such that I can use & at the end of the shell commands and each command to be executed one after the other! (I tried to put & simply at the end of each shell command with the result that each where started at the same time) Here is the plugin: ########################################################################### import os, string, re import util import sys import shutil from qltk import ErrorMessage from shutil import copy from plugins.songsmenu import SongsMenuPlugin class _Base(SongsMenuPlugin): PLUGIN_ICON = 'gtk-cdrom' PLUGIN_VERSION = '0.1' # XXX : pb potentiel: si deux utilisateurs utilisent ce plugin # en meme temps, ils vont se marcher sur les pieds... destdir = "/tmp/cd_QL" convert_cmd = "mplayer -ao pcm:file=%(dest)s %(source)s" normalize_cmd = "normalize -m %(path)s/*.wav" burn_cmd = "cdrecord -v -eject %(flags)s -pad -audio %(path)s/*.wav" burn_flags = '' def plugin_songs(self, songs): if not self.check_mplayer(): return self.setup() try: try: for num, song in enumerate(songs): self.makewav(song, num) self.normalize() self.burn() except Exception, e: ErrorMessage( None, "Unknown error", "An error occured while processing files:\n%s." % e ).run() finally: self.teardown() def check_mplayer(self): if not util.iscommand("mplayer"): ErrorMessage( None, "Mplayer not found", "Mplayer is used to convert files in wave files." ).run() return False return True def setup(self): os.mkdir(self.destdir) def makewav(self, song, num): source = song['~filename'].replace(" ", "\ ").replace("'","\\'") dest = os.path.join(self.destdir, "%03d.wav" % num) cmd = self.convert_cmd % dict(source=source, dest=dest) os.system(cmd) def normalize(self): os.system(self.normalize_cmd % dict(path=self.destdir)) def burn(self): flags = self.burn_flags cmd = self.burn_cmd % dict(path=self.destdir, flags=flags) os.system(cmd) def teardown(self): shutil.rmtree(self.destdir) class DAO(_Base): PLUGIN_ID = 'Burn CD w/o blanks' PLUGIN_NAME = _('Burn CD w/o blanks') PLUGIN_DESC = 'Burn CD w/o blanks.' burn_flags = '-dao' class TAO(_Base): PLUGIN_ID = 'Burn CD with blanks' PLUGIN_NAME = _('Burn CD with blanks') PLUGIN_DESC = 'Burn CD with blanks.' # on exporte seulement ces deux classes __all__ = ['DAO', 'TAO'] ############################################################################# and yeah, please consider that I am new to python and do understand something to the thread! Thanks in advance -- Brice Arch Linux (Linux user nb. 372699) ----- "Unix IS user friendly, it is just selective about who his friends are" From l.m.aangeenbrug at gmail.com Mon Nov 13 12:11:13 2006 From: l.m.aangeenbrug at gmail.com (lennart) Date: 13 Nov 2006 09:11:13 -0800 Subject: Is python for me? Message-ID: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> Hi, I'm planning to learn a language for 'client' software. Until now, i 'speak' only some web based languages, like php. As a kid i programmed in Basic (CP/M, good old days :'-) ) Now i want to start to learn a (for me) new computer language. I like Python. Its free, easy to learn and some favorite programs of my are written in Python / can understand Python (like OpenOffice) etc. But I'm not a full-time programmer. I know, that I've only time & possibility to learn one (= 1) language good. So i ask myself is python the language I'm looking for? In the future, i want to write the following applications: [*] A database driven program, which can handle my clients, tasks and places (= 3 tables, has to work relative with each other). I think, this isn't a problem for Python [*] As a photographer i like to build a picture management system (also db) with raw support. Raw is the raw-data from the sensor of the camera. My questions: - can python encode raw? - can python head for a utility like dcraw? - or head for a utility like IrfanView (delphi?) or something like that? Tnx for your help! From stefan.behnel-n05pAM at web.de Wed Nov 22 08:23:15 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 22 Nov 2006 14:23:15 +0100 Subject: Pyparsing Question. In-Reply-To: <1164188646.047093.182390@f16g2000cwb.googlegroups.com> References: <1164188646.047093.182390@f16g2000cwb.googlegroups.com> Message-ID: <45644F43.3050007@web.de> Ant wrote: > So I thought I'd look into the pyparsing module, but can't find a > simple example of processing random text. Have you looked at the examples on the pyparsing web page? Stefan From larry.bates at websafe.com Wed Nov 8 14:26:33 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 08 Nov 2006 13:26:33 -0600 Subject: Python deployment options. In-Reply-To: <1162986129.233443.268730@h54g2000cwb.googlegroups.com> References: <1162982262.010438.99260@f16g2000cwb.googlegroups.com> <1162985073.163257.110180@m73g2000cwd.googlegroups.com> <1162986129.233443.268730@h54g2000cwb.googlegroups.com> Message-ID: <45522F69.1080606@websafe.com> king kikapu wrote: > I see...So, if these are the only options, the only "safe" bet is to > install the language on the machine (beeing Win, Linux or Mac) > and execute the .py files, right ?? > > > On Nov 8, 1:24 pm, "Chris_147" wrote: >> king kikapu wrote: >>> Hi to all folks here, >>> i just bought a book and started reading about this language. >>> I want to ask what options do we have to deploy a python program to >>> users that do not have the labguage installed ?? >>> I mean, can i make an executable file, or something that contains the >>> runtime and the modules that the program only use or am i forced to >>> download the language to the user machine so the .py files can be run >>> ?? >>> Thanks in advance, >>> king kikapuWell, on Windows you have to look for the Py2Exe package >> (www.py2exe.org) >> On Mac OS X you can use Py2App >> (http://undefined.org/python/py2app.html) >> >> Mind you, on Windows there is one big potentional problem: Python is >> compiled with Visual Studio 2003 and needs msvcr71.dll. So Py2Exe >> wants to distribute that dll also, but if you don't have a valid Visual >> Studio license, you are not allowed to. >> It is explained further in this thread:http://groups.google.com/group/comp.lang.python/browse_frm/thread/bcc... >> >> I doubt Microsoft will unleash their lawyers on you, but it is a >> problem. > py2exe and py2app work extremely well. I'm not sure why you wouldn't want to use them if you want to distribute to those platforms. Actually they take the installed version of python out of the equation (at least I know py2exe does). -Larry From fredrik at pythonware.com Thu Nov 16 13:23:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 19:23:24 +0100 Subject: Python v PHP: fair comparison? In-Reply-To: <455CAA2E.5010708@tim.thechases.com> References: <136ED738BD4F1545B97E4AC06FF6370734BFDC@DMSP-MSG-EVS01.mail.pvt> <455CAA2E.5010708@tim.thechases.com> Message-ID: Tim Chase wrote: > I can't say I've come across any hosting places that serve up PHP > for $10/yr either...the closest I've found is about $3.50/mo > (which also provides Python CGI). https://www.nearlyfreespeech.net/about/faq.php#Average From fredrik at pythonware.com Sat Nov 11 18:18:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Nov 2006 00:18:28 +0100 Subject: Python Parallel Paradigm In-Reply-To: References: <1163272625.991469.153870@i42g2000cwa.googlegroups.com> <4556246a$0$326$e4fe514c@news.xs4all.nl> <1163276885.609160.163090@h54g2000cwb.googlegroups.com> Message-ID: Sandy wrote: > I usually lurk on the comp.lang.python newsgroup. I'm not an expert > in the slightest, but I have had a growing feeling that there's > something definitely lacking in the concurrency aspects of Python. the culprit in this case appears to be Microsoft's console library, though. I'm pretty sure that's not written in Python. From grenier.sylvain at gmail.com Thu Nov 2 16:38:21 2006 From: grenier.sylvain at gmail.com (mavicdog) Date: 2 Nov 2006 13:38:21 -0800 Subject: problem controlling/displaying video thru "pexpect" Message-ID: <1162503501.176338.133350@m7g2000cwm.googlegroups.com> I am developing a small appl. for a student to code some video. I am able to control mplayer in slave mode through IDLE using pexpect. In my app though I want to display it in a particular frame and have buttons control rw ff, stop, play etc... I am having two problems. One how do I frame the mplayer window once it is called? How do I execute the pexpect script I have working now from the app? I can post code if it helps. thanks. From smadim2 at grads.ece.mcmaster.ca Mon Nov 6 15:01:55 2006 From: smadim2 at grads.ece.mcmaster.ca (M.N.Smadi) Date: Mon, 06 Nov 2006 15:01:55 -0500 Subject: auto indent Message-ID: <454F94B3.5070204@grads.ece.mcmaster.ca> Hi there; i have a script that is not indented properly. Is there a way that i can have it auto indented. thanks moe smadi From noah.rawlins at comcast.net Tue Nov 21 20:36:05 2006 From: noah.rawlins at comcast.net (Noah Rawlins) Date: Tue, 21 Nov 2006 20:36:05 -0500 Subject: Is time.time() < time.time() always true? In-Reply-To: References: <2773CAC687FD5F4689F526998C7E4E5FF1EBCD@au3010avexu1.global.avaya.com> Message-ID: Ben Finney wrote: > Really? Where does Python guarantee that the left side *must* be > evaluated before the right side of a comparison? (If the right side > were to be evaluated first, the left might end up with a greater > value.) > http://docs.python.org/ref/evalorder.html From robert.kern at gmail.com Fri Nov 17 15:21:13 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 17 Nov 2006 14:21:13 -0600 Subject: Decimal() instead of float? In-Reply-To: <1163794251.5107.151.camel@pepper> References: <1163294604.4675.4.camel@pepper> <1163511997.4675.88.camel@pepper> <4559F828.7070704@holdenweb.com> <1163794251.5107.151.camel@pepper> Message-ID: Michael B. Trausch wrote: > I don't have (so far as I know) a 64-bit float available to me. Yes, you do: the regular Python float type. -- 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 evenprimes at gmail.com Thu Nov 9 14:13:21 2006 From: evenprimes at gmail.com (Chris Cioffi) Date: Thu, 9 Nov 2006 14:13:21 -0500 Subject: opening excel In-Reply-To: <4552d34b$1@quokka.wn.com.au> References: <4552d34b$1@quokka.wn.com.au> Message-ID: You can also check out the pyExcelerator project. http://sourceforge.net/projects/pyexcelerator It seems to work reasonably well at direct Excel file manipulation. However it isn't meant as a VBA replacement kind of thing. Chris On 11/9/06, at open-networks.net"@bag.python.org timmy <"timothy> wrote: > Hello, > > has anybody got any experience opening and manilpulating excel > spreedsheets via python? it seems pythoncom allows this to happen but > i'm a total newb to it. (i usually work in the unix world) > all i need to do, is open the xls files and read values from it. > -- > http://mail.python.org/mailman/listinfo/python-list > -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke From jstroud at mbi.ucla.edu Sat Nov 4 04:42:30 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 04 Nov 2006 09:42:30 GMT Subject: PySchool - Online Python Web Framework Workshop. In-Reply-To: <1162593399.583357.199570@e3g2000cwe.googlegroups.com> References: <1162593399.583357.199570@e3g2000cwe.googlegroups.com> Message-ID: RobJ wrote: > Hi! My Name is Rob Johnson and I am a graduate student at The Richard > Stockton College of NJ. To make a long story short, I'm working on my > Masters project in the MAIT program (Masters of Arts in Instructional > Technology). I have written a proposal to put together a free on-line > Python web framework workshop. The workshop will be geared to help > people new to Python web frameworks. I am asking for the community's > assistance to help me get this project off the ground. As part of my > project, I am conducting a survey for people who are interested in > learning more about python web frameworks. The survey is located at > http://killersurvey.com/answer_survey.php?id=479. I have also started a > blog about this experience in order to let people know what I'm doing > (http://pyschool.blogspot.com/). If you have a few minutes, please take > a couple of minutes to take the quick survey. The survey is anonymous > and the information will be used for statistics for my project. Also, > any constructive feedback or suggestions that you can give me would be > gladly appreciated. > > Thanks > > Rob J > Q9 should be "check all that apply" or otherwise qualified with "primarily". Q10 is missing other types of broadband such as what one might find at school, and also have the option of multiple selections. From sjmachin at lexicon.net Mon Nov 20 04:59:26 2006 From: sjmachin at lexicon.net (John Machin) Date: 20 Nov 2006 01:59:26 -0800 Subject: trying to create a dictionary in python, using variables as a value References: <1164008459.159792.48600@k70g2000cwa.googlegroups.com> Message-ID: <1164016765.497299.193830@b28g2000cwb.googlegroups.com> ronrsr wrote: > but I keep getting syntax errors on this one - On this one what? It would help very much if you showed the one statement that is getting the syntax error. > > > > adict = {'zid': result[0][0], 'keywords': result{0][1], > 'quotations':result[0][2],'citations':result[0]{3]}; > zhtml.print_update_form(adict); If you were to set out your code neatly, the *two* syntax errors would be somewhat more obvious on inspection, and would enable easy detection when you tried to load the file. # The following is meant to have the "result"s aligned vertically ... adict = { 'zid': result[0][0], 'keywords': result{0][1], 'quotations': result[0][2], 'citations': result[0]{3], } zhtml.print_update_form(adict) === C:\junk>ronsr2.py File "C:\junk\ronsr2.py", line 3 'keywords': result{0][1], ^ SyntaxError: invalid syntax > > result [0][0] = 22L > result [0].[1] = "Agricultural Subsidies, Global Trade', ' The above looks very much like a syntax error to me (dot between [0] and [1]) > > result[0][2]] = Lazio, Rick, "Some Trade Barrier1s Won\xe2\x80\x99t > Fall," The New York Times, 8/9/03\\r\\n" While not strictly syntax errors, I doubt very much whether Lazio and Rick are intentional variable names! And they're not (looking at "result" below)!! Why are you retyping all of this stuff? If you think it's a help with discovering why there's a syntax error in the first line, it's not a help, it's quite irrelevant. A syntax error means that the statement is not a valid Python statement -- nothing to do with the contents of any variables mentioned in the statement. > > result[0] [3] ='In 2002, the 30 industrial nations of the Organization > for Economic Cooperation and Development spent $311 billion on domestic > agricultural subsidies, which is more than the combined gross domestic > products of all the countries of sub-Saharan Africa. The World Bank > calculated that the European Union\xe2\x80\x99s annual subsidy to dairy > farmers comes out to $913 per cow; this dwarfs sub-Saharan > Africa\xe2\x80\x99s per capita gross domestic product of > $490.\xe2\x80\x9d\\r\\n \\r\\n \\r\\n > > result = ((22L, '((22L, 'Agricultural Subsidies, Global Trade', 'Lazio, > Rick, "Some Trade Barrier1s Won\xe2\x80\x99t Fall," The New York > Times, 8/9/03\\r\\n \\r\\n \\r\\n ', > '\xe2\x80\x9cIn 2002, the 30 industrial nations of the Organization for > Economic Cooperation and Development spent $311 billion on domestic > agricultural subsidies, which is more than the combined gross domestic > products of all the countries of sub-Saharan Africa. The World Bank > calculated that the European Union\xe2\x80\x99s annual subsidy to dairy > farmers comes out to $913 per cow; this dwarfs sub-Saharan > Africa\xe2\x80\x99s per capita gross domestic product of > $490.\xe2\x80\x9d\\r\\n \\r\\n \\r\\n '),)n ', > '\xe2\x80\x9cIn 2002, the 30 industrial nations of the Organization for > Economic Cooperation and Development spent $311 billion on domestic > agricultural subsidies, which is more than the combined gross domestic > products of all the countries of sub-Saharan Africa. The World Bank > calculated that the European Union\xe2\x80\x99s annual subsidy to dairy > farmers comes out to $913 per cow; this dwarfs sub-Saharan > Africa\xe2\x80\x99s per capita gross domestic product of > $490.\xe2\x80\x9d\\r\\n \\r\\n \\r\\n '),) > From steve at REMOVE.THIS.cybersource.com.au Sat Nov 4 00:41:20 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 04 Nov 2006 16:41:20 +1100 Subject: Physical constants References: <73D46C5F-12AE-4700-86D2-7FAE0DEF6C54@mac.com> Message-ID: On Fri, 03 Nov 2006 18:38:33 -0800, Rares Vernica wrote: > Hi, > > I am not sure how the constants are implemented in math, >>> import math >>> math.__file__ '/usr/lib/python2.4/lib-dynload/mathmodule.so' Looks like it is all done in C. It's probably just a binding to your platform's C floating point library. But regardless of where they come from, constants like pi are just regular Python names and objects. >>> math.pi 3.1415926535897931 >>> math.pi = 3 >>> math.pi 3 So not "real" constants, just constant-by-convention. Whether you call that a feature or a wart is up to you. But if you want actual constants that can't be re-bound, then look at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 Keep in mind that this carries a performance penalty. > but here is how > I would do it. The main idea is to declare the constants as globals in > some file. > > Declare all the constants in a file: > const.py > --- > pi = 3.14 > > Whenever you want to use pi from another file, just do: > somecode.py > --- > from const import pi Or just import const and refer to const.pi. That's arguably clearer, although again there is a tiny performance cost. -- Steven. From dsa at unilestemg.br Wed Nov 8 06:46:23 2006 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Wed, 8 Nov 2006 11:46:23 +0000 Subject: Python Jogos In-Reply-To: <1162992589.682760.282340@k70g2000cwa.googlegroups.com> References: <1162992589.682760.282340@k70g2000cwa.googlegroups.com> Message-ID: <200611081146.23829.dsa@unilestemg.br> Em Quarta 08 Novembro 2006 13:29, manelitoau at gmail.com escreveu: > Jogo da velha > Jogo do galo > Codigos em python kem me arranja ----> Please excuse me for talking in portuguese here, just want to show the better place for Manelito to ask this. Ol? Manelito, O idioma usado nessa lista ? o ingl?s, caso n?o se sinta a vontade em fazer pergutas em ingl?s, favor perguntar na lista do grupo pythonbrasil. Acesse o site a?: www.pythonbrasil.com.br At? -- Douglas Soares de Andrade msn: douglas at tuxfamily.org jabber: dsandrade at jabber.org Quote: Real programmers don't die, they just GoSub and Return. From cjw at sympatico.ca Fri Nov 10 09:48:52 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 10 Nov 2006 09:48:52 -0500 Subject: range syntax Message-ID: One of the little irritants of Python is that the range syntax is rather long-winded: [Dbg]>>> range(3, 20, 6) [3, 9, 15] [Dbg]>>> It would be nice if one could have something like 3:20:6. I've just come across the r_class in numpy which doesn't go that far but does provide a generalization of the above: [Dbg]>>> r_[1:6:2, 6:8, (10, 11, 13), [20,25]] array([ 1, 3, 5, 6, 7, 10, 11, 13, 20, 25]) [Dbg]>>> Colin W. From steve at REMOVE.THIS.cybersource.com.au Sun Nov 5 12:22:51 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 06 Nov 2006 04:22:51 +1100 Subject: forwarding *arg parameter References: <6pn3h.125$7b6.98@read3.inet.fi> Message-ID: On Sun, 05 Nov 2006 15:26:58 +0000, Tuomas wrote: > >>> def g(*arg): > ... return arg > ... > >>> g('foo', 'bar') > ('foo', 'bar') > >>> # seems reasonable The function g: - takes the arguments 'foo' and 'bar' - collects them in a tuple named 'arg' = ('foo', 'bar') - returns the tuple named arg > >>> g(g('foo', 'bar')) > (('foo', 'bar'),) The function g: - takes the argument ('foo', 'bar') - collects it in a tuple named 'arg' = (('foo', 'bar'),) - returns the tuple named arg The function is doing exactly the same as in the first case, except the arguments are different. > >>> # not so good, what g should return to get rid of the outer tuple Why do you want to? The way the function is now makes perfect sense. All argument types are treated in exactly the same way: g(string) => tuple containing string g(float) => tuple containing float g(int) => tuple containing int g(list) => tuple containing list g(instance) => tuple containing instance g(tuple) => tuple containing tuple You could write something like this: def g(*arg): # Detect the special case of a single tuple argument if len(arg) == 1 and type(arg[0]) == tuple: return arg[0] else: return arg but now tuple arguments are treated differently to all other data. Why do you think you need that? -- Steven From martin at v.loewis.de Fri Nov 3 18:40:27 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 04 Nov 2006 00:40:27 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> Message-ID: <454bd36c$0$2364$9b622d9e@news.freenet.de> robert schrieb: > in combination with some simple locking (anyway necessary) I don't see a > problem in ref-counting. In the current implementation, simple locking isn't necessary. The refcounter can be modified freely since the code modifying it will always hold the GIL. > ---- Question Besides: do concurrent INC/DEC machine OP-commands > execute atomically on Multi-Cores as they do in Single-Core threads? Not necessarily, no. On x86, you need to prefix the instruction with the LOCK prefix for it to become atomic. Otherwise, the two necessary read/write cycles to main memory may interleave with the memory operations of another processor. On other processors, INC might not exist at all as an instruction; when you only have register add, then implementing an atomic increment is a challenge. That's why the Windows API provides you with an atomic increment function as part of the operating system API. Regards, Martin From korvus at gmail.com Mon Nov 20 11:13:01 2006 From: korvus at gmail.com (Jeff Poole) Date: 20 Nov 2006 08:13:01 -0800 Subject: cPickle problems References: <1163722893.992949.295350@b28g2000cwb.googlegroups.com> <1163723175.530850.185990@m73g2000cwd.googlegroups.com> <1163724509.572724.199720@f16g2000cwb.googlegroups.com> <1163730111.641857.142850@k70g2000cwa.googlegroups.com> Message-ID: <1164039181.157901.72130@m73g2000cwd.googlegroups.com> > Jeff - > > Sorry not to reply sooner, I have been out of town with limited access to > c.l.py. Also, I didn't really pick up on "cPickle problems" as a > pyparsing-related post. :) > > I would be happy to make ParseResults picklable, I didn't realize that this > getattr behavior was defeating that capability. I have had people > successfully use pickle on pyparsing grammars, but have not had anyone > report any pickle experience with ParseResults objects, either pro or con. > > I have a test version of pyparsing with pickling support added, and it > passes my simple unit tests. I could send it to you if you would test it > against your program. > > -- Paul Paul, No problem, I think we've both been busy with other things. I was actually going to post something on the PyParsing wikispaces since I wasn't sure if you checked here. I wasn't actually intentionally pickling any ParseResults objects, but I realized that in my parse actions, I was making a copy of the "t" parameter, which is actually a ParseResults object. I switched my code to use t.asList() and things are ok now. If you'd like me to test your version, I'd be glad to, otherwise I can wait until whenever that change makes it's way into a release. Jeff From jeremit0 at gmail.com Thu Nov 2 11:41:13 2006 From: jeremit0 at gmail.com (jeremito) Date: 2 Nov 2006 08:41:13 -0800 Subject: string formatter for tuple In-Reply-To: References: <1162481557.791817.41690@b28g2000cwb.googlegroups.com> <454A126F.6040402@tim.thechases.com> Message-ID: <1162485673.291576.140470@h48g2000cwc.googlegroups.com> skip at pobox.com wrote: > >>>>> "Tim" == Tim Chase writes: > > >> How can I print a tuple with a single string format? > > Tim> print "a = %s" % str(a) > Tim> or > Tim> print "a = %s" % repr(a) > > Or wrap the tuple in a tuple: > > print "a = %s" % (a,) > > Skip Thank you all very much for your help. Jeremy From prouleau001 at gmail.com Wed Nov 29 13:02:09 2006 From: prouleau001 at gmail.com (prouleau001 at gmail.com) Date: 29 Nov 2006 10:02:09 -0800 Subject: Surprise with special floating point values In-Reply-To: <1164822818.252321.132680@j72g2000cwa.googlegroups.com> References: <1164822818.252321.132680@j72g2000cwa.googlegroups.com> Message-ID: <1164823329.366889.257820@h54g2000cwb.googlegroups.com> On Nov 29, 12:53 pm, prouleau... at gmail.com wrote: > Hi all, > > While trying to use simplejson under Python 2.4.3 I have been > investigating the handling of special floating point values and found > that both Python 2.4 and 2.5 return False when comparing a NaN with > itself. Although surprising, I imagine it could also be correct since > NaN is not a number. But is it correct? And of course it is correct... As NaN does not compare with itself in floating point: http://en.wikipedia.org/wiki/NaN Should have read it earlier... > -- > Pierre Rouleau From robin at reportlab.com Fri Nov 10 05:23:46 2006 From: robin at reportlab.com (Robin Becker) Date: Fri, 10 Nov 2006 10:23:46 +0000 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <4553AEA9.5040902@jessikat.plus.net> References: <1163072637.924217.90610@h54g2000cwb.googlegroups.com> <45533D9F.5020002@chamonix.reportlab.co.uk> <4553AEA9.5040902@jessikat.plus.net> Message-ID: <45545332.7090208@chamonix.reportlab.co.uk> Robin Becker wrote: > Andrew MacIntyre wrote: >> Robin Becker wrote: >> >>> I think it uses sysv semaphores and although freeBSD 6 has them >>> perhaps there's something I need to do to allow them to work. >> IIRC, you need to explicitly configure loading the kernel module, or >> compile the kernel with the necessary option in the config file. >> > I tried loading the module, but it seems already to be in the kernel. > Probably some sysctl stuff to do. > In fact the semaphore modules are built in now. I did some debugging and the error happens in the code at SemSet.c line 25 for (i = 0; i < sets; i++) { int id = semget(IPC_PRIVATE, MAX_SYSV_SET_SIZE, IPC_CREAT | S_IREAD | S_IWRITE); //SEM_R | SEM_A); if (id == -1) { the first semget(i=0) succeeds and the second fails with an errno ENOSPC which from the man page implies a resource issue of some kind. [ENOSPC] Insufficiently many semaphores are available. [ENOSPC] The kernel could not allocate a struct semid_ds. I guess the freebsd limits must be different to the original development environment. -- Robin Becker From bignose+hates-spam at benfinney.id.au Tue Nov 21 20:18:06 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 22 Nov 2006 12:18:06 +1100 Subject: Is time.time() < time.time() always true? References: <2773CAC687FD5F4689F526998C7E4E5FF1EBCD@au3010avexu1.global.avaya.com> Message-ID: <87bqn0wa7l.fsf@benfinney.id.au> "Delaney, Timothy (Tim)" writes: > So long as the clock on the machine it's running on is not set > backwards between the two calls, you can guarantee that > > time.time() <= time.time() > > will always evaluate true. Really? Where does Python guarantee that the left side *must* be evaluated before the right side of a comparison? (If the right side were to be evaluated first, the left might end up with a greater value.) -- \ "A free society is one where it is safe to be unpopular." -- | `\ Adlai Ewing Stevenson | _o__) | Ben Finney From fuzzyman at gmail.com Tue Nov 21 10:37:15 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 21 Nov 2006 07:37:15 -0800 Subject: best bet for using a .NET dll In-Reply-To: References: Message-ID: <1164123435.063450.325910@k70g2000cwa.googlegroups.com> Warren Jackson wrote: > I'd like to make a simple program that uses the Canon digital camera > SDK (EDSDK 1.3). Basically I need to take pictures and download them > to my computer. They have a fair amount of example code for the .NET > languages, and don't officially support anything else. > > The API uses more than the basic c types (references, etc.) that I'm > not totally familiar with yet. Included at the bottom is an example > of one of the functions. > > What is my best bet for writing this in Python? cTypes, IronPython, > something else? I haven't worked with either before but am currently > reading up. It seams cTypes has a difficult time dealing with > anything but the 'normal' c types, is this correct? > > Would it be easier to just write a program in C# to handle all of the > fancy types? (ie. make a function that opens and closes session, finds > camera, takes picture, downloads picture, saves picture - that can > then be read in python) ? This isn't a very attractive option to me. > > Thanks in advance for any insight. > This sounds like the sort of thing for which IronPython is ideal. It should eliminate the need for C# unless you have to mark classes with attributes (In which case you should be able to get away with a stub class.) Fuzzyman http://www.voidspace.org.uk/index2.shtml From prabhu at aero.iitb.ac.in Sat Nov 18 05:39:31 2006 From: prabhu at aero.iitb.ac.in (Prabhu Ramachandran) Date: Sat, 18 Nov 2006 16:09:31 +0530 Subject: [SciPy-user] About alternatives to Matlab In-Reply-To: <455E0496.4020703@bryant.edu> References: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> <1163711343.870829.110030@h48g2000cwc.googlegroups.com> <1163720268.611923.3180@e3g2000cwe.googlegroups.com> <455E0496.4020703@bryant.edu> Message-ID: <17758.58083.69027.862918@prpc.aero.iitb.ac.in> >>>>> "Brian" == Brian Blais writes: Brian> 3) 3D plotting requires yet-another library. luckily I Brian> haven't had to use this much, but I hope that someday that Brian> it will be part of matplotlib. I'd rather not say anything about this since I have strong opinions about the subject. Brian> 4) GUI development is a bit easier in Matlab for small Brian> projects, and harder for larger ones. I like using wax in Brian> python, which wraps wxPython. Others swear by Dabo, but I Brian> always get two windows popping up when I run even the hello Brian> world daboui program. At any rate, wxPython looks much Brian> better on Windows than the same interface in Matlab, and it Brian> is more robust across operating systems. You should try and take a look at enthought.traits. It makes creating UIs a lot easier than anything else I've seen. cheers, prabhu From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Nov 10 16:22:53 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 10 Nov 2006 22:22:53 +0100 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> <4rjlkqFrlskqU1@mid.individual.net> <4rk5giFrerjfU1@mid.individual.net> Message-ID: <4rk8tdFrsq8fU1@mid.individual.net> Fredrik Lundh wrote: > >>> color = "blue" > >>> if color == "red" or "green" or "yellow": > ... print color, "is red or green or yellow" > ... > blue is red or green or yellow Whoops. Okay. Regards, Bj?rn -- BOFH excuse #303: fractal radiation jamming the backbone From rtw at freenet.co.uk Tue Nov 28 07:41:42 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 28 Nov 2006 06:41:42 -0600 Subject: Accessing file metadata on windows XP References: <1164704134.100569.101270@j72g2000cwa.googlegroups.com> Message-ID: wrote in news:1164704134.100569.101270 at j72g2000cwa.googlegroups.com in comp.lang.python: > When rightclicking a, for example, pdf file on windows, one normally > gets a screen with three or four tags. Clicking on one of the summary > tag one can get some info like "title", "Author", "category", "keyword" > etc.. > > My question is how can I programmatically read and change these data > with python. I know I should use Hammond's win32 extension, somehow > involving the pythoncom, storagecon of win32com etc.. Unfortunately, > so far I cannot get anything useful. Instead of trying blindly, would > somebody please points me to the correct direction. A little snippet > would help. I am particular interested in pdf files. > This looks like it might be useful: Thats: MSDN Home > MSDN Library > Win32 and COM Development > User Interface > Windows Shell > Windows Shell > Shell Objects for Scripting and Microsoft Visual Basic > ShellFolderItem > Rob. -- http://www.victim-prime.dsl.pipex.com/ From jm.suresh at gmail.com Sun Nov 5 08:29:19 2006 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 5 Nov 2006 05:29:19 -0800 Subject: string to list of numbers conversion In-Reply-To: References: <1162730071.953080.284980@i42g2000cwa.googlegroups.com> Message-ID: <1162733359.612568.149870@f16g2000cwb.googlegroups.com> Peter, Thanks. This recipe fails when negative numbers are used. safe_eval('(12, -12)') *** Unsafe_Source_Error: Line 1. Unsupported source construct: compiler.ast.UnarySub But, I think it could be easily fixed for somebody who understands the script. Can somebody help. Thanks. Suresh Peter Otten wrote: > jm.suresh at no.spam.gmail.com wrote: > > > I have a string '((1,2), (3,4))' and I want to convert this into a > > python tuple of numbers. But I do not want to use eval() because I do > > not want to execute any code in that string and limit it to list of > > numbers. > > Is there any alternative way? > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 > > Peter From shejo284 at gmail.com Tue Nov 7 15:27:00 2006 From: shejo284 at gmail.com (Sheldon) Date: 7 Nov 2006 12:27:00 -0800 Subject: C wrapper In-Reply-To: References: <1162928252.643092.23350@h48g2000cwc.googlegroups.com> <1162930226.658619.79830@m73g2000cwd.googlegroups.com> Message-ID: <1162931220.448328.108160@e3g2000cwe.googlegroups.com> Robert Kern skrev: > Sheldon wrote: > > > This function is there and is called init_mymodule() but I have other > > functions that are not static. > > Is the module's name "_mymodule"? Or is it "mymodule"? > > -- > 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 Here is the file/module name: _msgpps_functions.c Here is the initfunction: PyMODINIT_FUNC init_msgpps_functions(void) { PyObject* m; m=Py_InitModule("_msgpps_functions",_msgpps_functionsMethods); ErrorObject = PyString_FromString("_msgpps_functions.error"); if(ErrorObject == NULL || \ PyDict_SetItemString(PyModule_GetDict(m),"error",ErrorObject)!=0) { Py_FatalError("Can't define _msgpps_functions.error"); import_array(); } /* access to Numeric PyArray functions */ } I have not main() function in the file. Instead the main function is called the same name: static PyObject* _msgpps_functions(PyObject* self, PyObject* args) Now I am new at this and I have been reading anything I can find. The only thing that is out of place is the part which I didn't include: /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initspam(); because I still don't understand this part. /sheldon From fredrik at pythonware.com Sun Nov 19 11:25:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Nov 2006 17:25:04 +0100 Subject: Why isn't SPLIT splitting my strings In-Reply-To: <1163952691.372592.76110@k70g2000cwa.googlegroups.com> References: <1163931285.390782.130500@h54g2000cwb.googlegroups.com> <1163932286.420652.100100@f16g2000cwb.googlegroups.com> <1163952617.270591.279730@j44g2000cwa.googlegroups.com> <1163952691.372592.76110@k70g2000cwa.googlegroups.com> Message-ID: John Henry wrote: > Oops! for cases like this, writing "[" + re.escape(charset) + "]" is usually a good way to avoid repeated oops:ing. > newString= re.split("[; ()\[\]", result) >>> newString= re.split("[; ()\[\]", result) Traceback (most recent call last): ... sre_constants.error: unexpected end of regular expression From bj_666 at gmx.net Thu Nov 2 10:40:48 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 02 Nov 2006 16:40:48 +0100 Subject: creating new objects with references to them References: <1162480549.786082.290980@b28g2000cwb.googlegroups.com> Message-ID: In <1162480549.786082.290980 at b28g2000cwb.googlegroups.com>, JohnJSal wrote: > What I don't know how to do is handle this arbitrary number of objects. > When it comes time to save the data to the DB, how do I access each > object (to get the text fields associated with each)? Won't I have to > have given each instance some name? Or is there some other way to do > this? Simply creating a new instance each time the user presses "New > Record" won't be good enough, because how do I retain a reference to > that instance over the course of the program, even after a second or > third instance has been created? Put your objects into a list. Each time the user presses the `New` Button append a new researcher object to it. Ciao, Marc 'BlackJack' Rintsch From triode at xnet.co.nz Thu Nov 30 17:05:13 2006 From: triode at xnet.co.nz (triode at xnet.co.nz) Date: 30 Nov 2006 14:05:13 -0800 Subject: detecting that a SQL db is running In-Reply-To: References: <783tm2dmb6brnptr91hsfnc1t38u1utbi8@4ax.com> Message-ID: <1164924313.495569.311330@80g2000cwy.googlegroups.com> Sorry if i did not make myself clear. let me try again. 1. I have a series of servers running windows server 2003. 2 on each server there is an application running that communicates with remote devices using email. 3. this application is made up from a series of modules that also extract data from a local MSDE db. 4. this application pulls emails from remote devices, interrogates a the DB, then passes on an XML message to a central server. 5. I am intercepting these XML messages to insert additional data that I extract from the DB, and then forward on to another application. Call this my local app. The problem that I have is that the original application occasionally hangs, causing the DB to stop. I have ASR routines in place to re-boot the server when this happens. I can detect when the db is up and not responding, however, if the DB does not start at all, my local application hangs. I need to find a way to determine if the DB has started, that's all. if any of you have any insight into how I can detect that the DB has started as is running, that would be very useful. any contributions, most gratefully received. kind regards bill From timothy at open-networks.net Thu Nov 9 03:46:53 2006 From: timothy at open-networks.net (timmy) Date: Thu, 09 Nov 2006 18:46:53 +1000 Subject: opening excel In-Reply-To: <1163058244.735201.62830@h48g2000cwc.googlegroups.com> References: <4552d34b$1@quokka.wn.com.au> <1163058244.735201.62830@h48g2000cwc.googlegroups.com> Message-ID: <4552ea87@quokka.wn.com.au> John Machin wrote: > timmy wrote: > >>Hello, >> >>has anybody got any experience opening and manilpulating excel >>spreedsheets via python? it seems pythoncom allows this to happen but >>i'm a total newb to it. (i usually work in the unix world) >>all i need to do, is open the xls files and read values from it. > > > If you really mean "read" rather than "manipulate", have a look at the > xlrd package (of which I'm the author). > > http://www.python.org/pypi/xlrd > > BTW, it's pure Python; you can run it on your unix box if you like :-) > > Cheers, > John > sweet thats what i'd like to do From nick at craig-wood.com Tue Nov 14 12:30:04 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 14 Nov 2006 11:30:04 -0600 Subject: Using signal.alarm to terminate a thread References: <12lgk7h55lu0vb4@corp.supernews.com> <12lj35aqa9drd8a@corp.supernews.com> Message-ID: Fredrik Lundh wrote: > Nick Craig-Wood wrote: > > > The only sensible things you can do from a signal handler is set a > > global flag, or call sem_post on a semaphore, to record the delivery > > of the signal. The remainder of the program can then either poll the > > global flag, or use sem_wait() and sem_trywait() on the semaphore. > > but that's exactly what Python's signal handlers do, right ? > > (the interpreter uses a "pending call" queue to collect events, and > executes them from the interpreter main loop in a controlled > fashion). Yes you are absolutely right >From http://docs.python.org/lib/module-signal.html Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), or pause(); only the main thread can set a new signal handler, and the main thread will be the only one to receive signals (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can't be used as a means of inter-thread communication. Use locks instead. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tuomas.vesterinen at pp.inet.fi Mon Nov 6 08:03:55 2006 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Mon, 06 Nov 2006 13:03:55 GMT Subject: forwarding *arg parameter In-Reply-To: References: <6pn3h.125$7b6.98@read3.inet.fi> <2Fp3h.195$7b6.100@read3.inet.fi> Message-ID: <%oG3h.107$8a7.65@read3.inet.fi> Steven D'Aprano wrote: > On Sun, 05 Nov 2006 19:35:58 +0000, Tuomas wrote: > > >>Thanks. My solution became: >> >> >>> def flattern(arg): >>... result = [] >>... for item in arg: >>... if isinstance(item, (list, tuple)): >>... result.extend(flattern(item)) >>... else: >>... result.append(item) >>... return tuple(result) >>... >> >>> def g(*arg): >>... arg = flattern(arg) >>... return arg >>... >> >>> def f(*arg): >>... return g(arg) >>... >> >>> f('foo', 'bar') >>('foo', 'bar') > > > > That's the most complicated do-nothing function I've ever seen. Here is a > shorter version: > > def shortf(*args): > return args > > > >>>>f('foo', 'bar') > > ('foo', 'bar') > >>>>shortf('foo', 'bar') > > ('foo', 'bar') > > >>>>f(1,2,3,4) > > (1, 2, 3, 4) > >>>>shortf(1,2,3,4) > > (1, 2, 3, 4) > > >>>>f({}, None, 1, -1.2, "hello world") > > ({}, None, 1, -1.2, 'hello world') > >>>>shortf({}, None, 1, -1.2, "hello world") > > ({}, None, 1, -1.2, 'hello world') > > Actually, they aren't *quite* identical: your function rips lists apart, > which is probably not a good idea. > > >>>>f("foo", [1,2,3], None) # three arguments turns into five > > ('foo', 1, 2, 3, None) > >>>>shortf("foo", [1,2,3], None) # three arguments stays three > > ('foo', [1, 2, 3], None) > > > > I still don't understand why you are doing this. Can we have an example of > why you think you need to do this? If i redefine the function g the difference comes visible: >>> def g(*arg): ... if with_flattern: arg=flattern(arg) ... return arg >>> with_flattern=False >>> f('foo', 'bar') (('foo', 'bar'),) >>> with_flattern=True >>> f('foo', 'bar') If you read the whole chain you find out what we were talking of. TV From grahamd at dscpl.com.au Tue Nov 14 06:07:00 2006 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 14 Nov 2006 03:07:00 -0800 Subject: mod_python installation problem ..severity High References: <1163499937.692984.101720@h48g2000cwc.googlegroups.com> Message-ID: <1163502420.173353.21060@k70g2000cwa.googlegroups.com> boney wrote: > On doing this and duly following the installation and testing > instructions at www.modpython.org and then pointing the url as > http://localhost/test/mptest.py, i get the following error on the > server log file: > > [Tue Nov 14 15:17:47 2006] [error] make_obcallback: could not import > mod_python.apache.\n > [Tue Nov 14 15:17:47 2006] [error] make_obcallback: Python path being > used "['C:\\\\Program Files\\\\Apache > Group\\\\Apache2\\\\bin\\\\python24.zip', '.\\\\DLLs', '.\\\\lib', > '.\\\\lib\\\\plat-win', '.\\\\lib\\\\lib-tk', 'C:\\\\Program > Files\\\\Apache Group\\\\Apache2\\\\bin']". > [Tue Nov 14 15:17:47 2006] [error] python_handler: no interpreter > callback found. > [Tue Nov 14 15:17:47 2006] [error] [client 127.0.0.1] python_handler: > Can't get/create interpreter. Your registry settings for Python do not include the site-packages directory where mod_python typically gets installed. Thus, trying updating the registry to add the site-packages directory. As a guide, see the following post from the mod_python mailing list archive as a guide. http://www.modpython.org/pipermail/mod_python/2006-September/021979.html This is for Python 2.5, but should give an indicator of what to look for. Update the PythonPath entry. For any mod_python help in the future, suggest you subscribe to the mod_python mailing list and ask your question there as there is a higher concentration of people there who are familiar with the software. Details of the mod_python mailing list are on the mod_python web site. Graham From steve at holdenweb.com Thu Nov 2 10:36:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Nov 2006 15:36:59 +0000 Subject: creating new objects with references to them In-Reply-To: <1162480549.786082.290980@b28g2000cwb.googlegroups.com> References: <1162480549.786082.290980@b28g2000cwb.googlegroups.com> Message-ID: JohnJSal wrote: > It seems like what I want to do is something that programmers deal with > everyday, but I just can't think of a way to do it. Basically, I am > writing a DB front-end and I want a new "Researcher" object to be > created whenever the user presses the "New Record" button. He can open > as many new records at a time as he wants and fill in the information. > Seems straightforward. > What I don't know how to do is handle this arbitrary number of objects. > When it comes time to save the data to the DB, how do I access each > object (to get the text fields associated with each)? Won't I have to > have given each instance some name? Or is there some other way to do > this? Simply creating a new instance each time the user presses "New > Record" won't be good enough, because how do I retain a reference to > that instance over the course of the program, even after a second or > third instance has been created? > Start with an empty list, and append new instances to it. Then when the user indicated completion you can iterate over the list INSERTing them into the database (presumably INSERTing the new researcher's details first). To minimize consistency problems it would help to make all of these insertions as a single database transaction. > Hope that makes sense. It seems like such a common task. > regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From aahz at pythoncraft.com Tue Nov 14 10:46:00 2006 From: aahz at pythoncraft.com (Aahz) Date: 14 Nov 2006 07:46:00 -0800 Subject: PyFAQ: anyone seen aahz' thread tutorial ? References: Message-ID: In article , Fredrik Lundh wrote: > >and yes, has anyone seen Aahz or his OSCON2001 thread tutorial slides >lately ? as noticed here: > > http://effbot.org/pyfaq/how-do-i-program-using-threads.htm > >they have disappeared from the starship? any ideas where to look for them ? Just a public note that I'm aware of the problem and have sent e-mail privately to Fredrik, just haven't had enough cycles to fix it.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 1993 From ptmcg at austin.rr._bogus_.com Sat Nov 18 07:27:54 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 18 Nov 2006 12:27:54 GMT Subject: MAKE GOOD MONEY BY INTERNET References: <1163848933.731124.307470@e3g2000cwe.googlegroups.com> Message-ID: Congratulations, Ciad, you have just posted your e-mail, that is claureal81 at yahoo.it, on Usenet, where it will get picked up by spammers the world over. I hope you get your $6000+!!!, so you can spend it on bootleg, discount, old versions of MS Office, C.I.A.L.I.S, and discount PHAayrRMAcies. Or perhaps forward it to Egineer Robson of Nigeria, who will happily send you 25hile of $US7.7Million all in 100 dollar bills in return. That e-mail again, claureal81 at yahoo.it. Is there no way to filter this kind of junk, short of going to a moderated list? -- Paul From akhtarkhan06 at rediffmail.com Tue Nov 28 05:48:31 2006 From: akhtarkhan06 at rediffmail.com (akhtar) Date: 28 Nov 2006 02:48:31 -0800 Subject: How to secure your network Message-ID: <1164710911.653304.34120@l39g2000cwd.googlegroups.com> How to secure your network Check this article to know how a network analyzer continuously monitors traffic on network and provides detailed information about critical problems, virus attacks and even generates traffic to stress test your network http://www.network-analyzer.blogspot.com From deets at nospam.web.de Thu Nov 23 11:00:49 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 23 Nov 2006 17:00:49 +0100 Subject: Does only emacs and idle support symbolic debugging? References: Message-ID: <4sluthFvvkteU1@mid.uni-berlin.de> Victor Ng wrote: > Subject line pretty much says it all - are those the only two editors > that support running the symbolic debugger from inside the editor? Nope, eric for example does as well. And I presume komodo will do that also. Diez From Sebastien.Boisgerault at gmail.com Fri Nov 24 12:37:58 2006 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 24 Nov 2006 09:37:58 -0800 Subject: Pydev configuration Message-ID: <1164389878.833569.60710@l39g2000cwd.googlegroups.com> Hi, Did anyone managed to change the code font family/size in Pydev (Python Editor Plugin for Eclipse) ? I found how to change the color mapping (Windows/Preference/Pydev) but did not found the font setting. Cheers, SB From ptmcg at austin.rr._bogus_.com Mon Nov 6 05:36:34 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 06 Nov 2006 10:36:34 GMT Subject: Python Distilled References: <1162790565.418382.237050@m73g2000cwd.googlegroups.com> Message-ID: "Marc 'BlackJack' Rintsch" wrote in message news:pan.2006.11.06.10.11.35.335058 at gmx.net... > In <1162790565.418382.237050 at m73g2000cwd.googlegroups.com>, Simon Wittber > wrote: > >> I'd also like to remove any deprecated or stuff which is left in for >> backwards functionality (eg Classic classes). > > Classic classes are still needed for exceptions: > >>>> class E(object): > ... pass > ... >>>> raise E > Traceback (most recent call last): > File "", line 1, in > TypeError: exceptions must be classes, instances, or strings (deprecated), > not type > > Ciao, > Marc 'BlackJack' Rintsch I thought exceptions were converted to new-style classes for Py2.5 (http://docs.python.org/whatsnew/pep-352.html). I've not upgraded yet, so cannot easily test this - under what version of Python was your posted code run? -- Paul From mccredie at gmail.com Fri Nov 17 15:20:36 2006 From: mccredie at gmail.com (Matimus) Date: 17 Nov 2006 12:20:36 -0800 Subject: remove a list from a list In-Reply-To: References: <455E0046.1090005@tim.thechases.com> <455E0A20.9000509@tim.thechases.com> <455E100D.8030100@tim.thechases.com> Message-ID: <1163794836.375856.111350@j44g2000cwa.googlegroups.com> > The solution so far is: > > for i in xrange(len(dirs), 0, -1): > if dirs[i-1].lower() in dirs_exclude: > del dirs[i-1] This won't affect much, but uses better style I think. Change: for i in xrange(len(dirs),0,-1): To: for i in reversed(xrange(len(dirs))): and then just use 'i' instead of 'i-1' From bernhard.voigt at gmail.com Tue Nov 7 11:58:50 2006 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: 7 Nov 2006 08:58:50 -0800 Subject: sound processing modules in python - anyone? In-Reply-To: <1162909648.042525.172190@i42g2000cwa.googlegroups.com> References: <1162909648.042525.172190@i42g2000cwa.googlegroups.com> Message-ID: <1162918730.681389.55330@m7g2000cwm.googlegroups.com> Hi, you might want to take a look at pyaudio. A module to read and write audio files. It is based on numpy and wraps the libsndfile library to use it from python. With the capabilites of numpy and scipy you probably have all you need. Here's a link to pyaudio http://www.ar.media.kyoto-u.ac.jp/members/david/softwares/pyaudio/index.html Here you find numpy and scipy: http://scipy.org/SciPy Enjoy! Bernhard From jonas.esp at googlemail.com Thu Nov 23 18:36:56 2006 From: jonas.esp at googlemail.com (GinTon) Date: 23 Nov 2006 15:36:56 -0800 Subject: Access to variable from external imported module In-Reply-To: References: <1164316786.875306.276460@h54g2000cwb.googlegroups.com> <1164319761.451409.196660@j44g2000cwa.googlegroups.com> Message-ID: <1164325016.139659.271500@l12g2000cwl.googlegroups.com> Thanks Robert, the best solution is get all local variables, else is impossible access to them. robert ha escrito: > GinTon wrote: > > I would to access to values that are created locally in that method > > after the method has executed? usually the return value? > or you want to get all local variables, then make a func/method > > def f(a=1): > b=2 > c=3 > return locals() #X/Object(locals()) > > -------- > > d=module.f() > print d['c'] # d.c From skip at pobox.com Mon Nov 6 12:37:39 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 6 Nov 2006 11:37:39 -0600 Subject: missing collections module In-Reply-To: References: Message-ID: <17743.29411.835485.300324@montanaro.dyndns.org> Shea> I am getting this error in a python script: Shea> File "/usr/sfw/lib/python2.3/site-packages/BTL/cache.py", line 12, in ? Shea> from collections import deque Shea> ImportError: No module named collections Shea> Where can I download the python collection module? You're probably using a package which is not supported under Python 2.3. The collections module is new with 2.4. Try upgrading to 2.4 or 2.5. Skip From m.elston at advantest-ard.com Thu Nov 16 20:38:28 2006 From: m.elston at advantest-ard.com (Mark Elston) Date: Thu, 16 Nov 2006 17:38:28 -0800 Subject: Writing to Registry In-Reply-To: References: Message-ID: <12lq4cishnjid23@corp.supernews.com> Note: this is untested (since I don't like screwing around in the registry...) Have you tried using REG_DWORD? Mark * Samantha wrote (on 11/16/2006 3:48 PM): > I am working with this recipes: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66011 > > The problem I am having is setting a hex value. > This line --- SetValueEx(aKey,"MyNewKey",0, REG_SZ, > r"c:\winnt\explorer.exe") > I want something Like -- SetValueEx(aKey,"MyNewSize",0, REG_SZ, 120 or > some value) > Help would be appreciated. > S > > From pydecker at gmail.com Fri Nov 10 22:48:27 2006 From: pydecker at gmail.com (Peter Decker) Date: Fri, 10 Nov 2006 22:48:27 -0500 Subject: How to choose the right GUI toolkit ? In-Reply-To: <1163092380.301382.113470@m7g2000cwm.googlegroups.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163092380.301382.113470@m7g2000cwm.googlegroups.com> Message-ID: On 9 Nov 2006 09:13:00 -0800, Dan Lenski wrote: > Nick and John S., thank you for the tip on wxPython! I'll look into it > for my next project. I too would avoid Qt, not because of the GPL but > simply because I don't use KDE under Linux and because Qt is not well > supported under Cygwin or on native Windows. I too like to learn from > actual printed books, so I'll check this one out. O'Reilly should do a > book on Python GUI stuff! > > John H.: thanks for pointing out pythoncard. This looks like it might > be an excellent substitute for LabView-like GUIs, which all my > coworkers like. I personally refuse to read or write LabView code, on > the grounds that its syntax causes severe brain damage and is > completely unportable. But that's a flame for another thread, so to > speak... You should also take a look at Dabo. Like PythonCard, it wraps wxPython, but it completely does away with the whole getter/setter approach, the ugly ALL_CAPS_CONSTANTS that wxPython unfortunately inherited from its C++ roots, and all those other non-Pythonic irritants. While Dabo is a complete 3-tier framework for developing database apps, you can just use the GUI tier. I don't do database stuff, and so I just use the dabo.ui module. Their URL is http://dabodev.com. -- # p.d. From robert.kern at gmail.com Fri Nov 17 17:13:21 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 17 Nov 2006 16:13:21 -0600 Subject: Decimal() instead of float? In-Reply-To: <1163800304.5107.179.camel@pepper> References: <1163294604.4675.4.camel@pepper> <1163511997.4675.88.camel@pepper> <4559F828.7070704@holdenweb.com> <1163794251.5107.151.camel@pepper> <1163800304.5107.179.camel@pepper> Message-ID: Michael B. Trausch wrote: > Perhaps you should not make assumptions; I am sure that you have heard > what they do at some point before. While *some* of the error doesn't > propagate as expected (which is actually a problem in itself?equations > no longer make sense if they are not mathematically balanced!) some > does. It is unpredictable and can't be tolerated when the numbers must > come out exactly. Okay, whatever your requirements are, Fredrik is certainly right in that you don't know what you're talking about with respect to floating point arithmetic. Please read the paper "What Every Computer Scientist Should Know About Floating-Point Arithmetic": http://docs.sun.com/source/806-3568/ncg_goldberg.html You would also do well to get a book on basic numerical analysis. If you have any transcendental functions involved (and if you are computing distances between geographical coordinates, you certainly will), you will encounter numbers that are irrational; that is, they *cannot* be expressed exactly in any finite form. Decimal() and GMP are *arbitrary* precision data types, not infinite. I admit, I am curious now about the application that you think requires these exact results. What operations are you actually performing? Surely there's a square root or trig function in there somewhere. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Sat Nov 25 10:21:34 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 25 Nov 2006 16:21:34 +0100 Subject: problem with global variable in a module In-Reply-To: <1164463795.849460.124060@j72g2000cwa.googlegroups.com> References: <1164463795.849460.124060@j72g2000cwa.googlegroups.com> Message-ID: <4sr5bvF110fjlU1@mid.uni-berlin.de> hollowspook schrieb: > def aa(): > global b > b=b+1 > print b > > b=1 > aa() > > The above code runs well in python shell. > > However I have a problem as follows. > > new a file named test.py > ------------------------------------------------------------------------ > > def aa(): > global b > b=b+1 > print b > ------------------------------------------------------------------------- > > Then in python shell, > > from test import * > b=1 > aa() > > The error message is : > Traceback (most recent call last): > File "", line 1, in ? > File "test.py", line 3, in aa > b=b+1 > NameError: global name 'b' is not defined > > Why this happens? Please do me a favor. Because python does not know "real" globals - globals are always only global on a module level. Now using the "from module import *"-syntax asks for trouble. Because your global b above is global to the __main__-module, not to the module test. But the aa-function expects it to live in tests. To make your example work, do it as this: import test test.b = 1 test.aa() See http://effbot.org/pyfaq/tutor-whats-the-difference-between-import-foo-and-from-foo-import.htm Diez From martin at v.loewis.de Sun Nov 5 06:08:40 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 05 Nov 2006 12:08:40 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <7x7iyafg85.fsf@ruckus.brouhaha.com> References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <454bd36c$0$2364$9b622d9e@news.freenet.de> <454ca6b4$0$151$9b622d9e@news.freenet.de> <7xpsc33zmh.fsf@ruckus.brouhaha.com> <454d587d$0$4361$9b622d9e@news.freenet.de> <7x7iyafg85.fsf@ruckus.brouhaha.com> Message-ID: <454DC638.2050802@v.loewis.de> Paul Rubin schrieb: > I dunno about x86 hardware signals but these instructions do > read-modify-write operaitons. That means there has to be enough > interlocking to prevent two cpu's from updating the same memory > location simultaneously, which means the CPU's have to communicate. > See (I think this is > how the current x86's do it): Ah, but in the case where the lock# signal is used, it's known that the data is not in the cache of the CPU performing the lock operation; I believe it is also known that the data is not in the cache of any other CPU. So the CPU performing the LOCK INC sequence just has to perform two memory cycles. No cache coherency protocol runs in that case. But even when caching is involved, I don't see why there should be more than three memory cycles. The MESI "protocol" really consists only of two pins: HIT# and HITM#; the actual implementation is just in keeping the state for each cache line, and in snooping. There CPU's don't really "communicate". Instead, if one processor tries to fill a cache line, the others snoop the read, and assert either HIT# (when they have not modified their cache lines) or HITM# (when they do have modified their cache lines). Assertions of these signals is also immediate. The worst case would be that one processor performs a LOCK INC, and another processor has the modified value in its cache line. So it needs to first flush the cache line, before the other processor can modify the memory. If the memory is not cached yet in another processor, the MESI protocol does not involve additional penalties. Regards, Martin From fredrik at pythonware.com Thu Nov 16 13:15:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 19:15:37 +0100 Subject: Has anyone generated Open Office Calc XML files from python In-Reply-To: <1163696586.682642.118450@m7g2000cwm.googlegroups.com> References: <1163696586.682642.118450@m7g2000cwm.googlegroups.com> Message-ID: vj wrote: > I have a program which generates xml files for excel but these files > are not recognized by open office calc. I looked at the OO uno library, > but it seems like an over kill. this could be a start: http://ooopy.sourceforge.net/ From bill_maxwell_notMyRealAddress at notreal.net Fri Nov 10 22:34:19 2006 From: bill_maxwell_notMyRealAddress at notreal.net (Bill Maxwell) Date: Fri, 10 Nov 2006 22:34:19 -0500 Subject: How to choose the right GUI toolkit ? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163015347.164393.74110@i42g2000cwa.googlegroups.com> <6ov7l2lb9ip2u5jmd54e2kso1s78fc68bb@4ax.com> <1163139352.206221.213180@m73g2000cwd.googlegroups.com> <1163141290.868726.11330@h48g2000cwc.googlegroups.com> Message-ID: <43hal2p6ep7vds2nl55uqil7v7i3guncl2@4ax.com> On 9 Nov 2006 22:48:10 -0800, "John Henry" wrote: >Upon closer look, the walkthrough did say: > >*************************** >from PythonCard import model > >Change that so it says: > >from PythonCard import dialog, model > >Save the code. >*************************** > >So, it works. Thanks for looking into it. It sounds like either it has been fixed in the newer version -- or I didn't do something correctly. It's been a long time, and I was just going by the notes I made back then. > > > >John Henry wrote: >> Bill Maxwell wrote: >> > On 8 Nov 2006 11:49:07 -0800, "John Henry" >> > wrote: >> > >> > > >> > >John Salerno wrote: >> > >> Dan Lenski wrote: >> > >> >> > >> > So, is there another toolkit I should be looking at? >> > >> >> > >> I highly recommend wxPython. It's very mature, full-featured, and >> > >> portable, and fairly easy to learn as well. I can't really compare it to >> > >> other toolkits (not having used any of them, except Tkinter), but it's >> > >> definitely one of the most popular and well-supported ones out there. >> > >> >> > >> http://www.wxpython.org/ >> > > >> > >I highly recommend that you try PythonCard (which sits on top of >> > >wxPython). You can get productive very very quickly. Take a look at: >> > > >> > >http://pythoncard.sourceforge.net/walkthrough1.html >> > >> > >> > I took a brief look at PythonCard almost a year ago and got discouraged >> > by what I found, so I stopped looking at it. I've inserted my notes >> > from back then, below. Does anybody know if these things have been >> > fixed in the latest release? >> > >> > Bill >> > >> > >> > ===================================================================== >> > My notes from Fri Dec-23-2005: >> > >> > This is a list of gripes I have while trying to learn about PythonCard. >> > I'm trying to investigate various GUI builders for Python, and >> > PythonCard looks promising, but a lot of things are getting in the way. >> > >> > I installed yesterday, using this installer: >> > PythonCard-0.8.1.FIXED.win32.exe >> > >> > A) The very first example in the tutorial is wrong! >> > >> > On this page: http://pythoncard.sourceforge.net/documentation.html >> > When you follow this link to try something for the very first time: >> > >> > Getting Started in PythonCard by Dan Shafer: >> > http://pythoncard.sourceforge.net/walkthrough1.html >> > >> > You quickly see that the minimal.py example doesn't even contain >> > this line, even though the tutorial refers to it: >> > >> >> I am not sure which one you are referring to but in the >> PythonCard\samples\minimal, you will find a minimal.py that says: >> >> #!/usr/bin/python >> >> """ >> __version__ = "$Revision: 1.8 $" >> __date__ = "$Date: 2005/12/17 15:20:02 $" >> """ >> >> from PythonCard import model >> >> >> class Minimal(model.Background): >> def on_menuFileAbout_select(self, event): >> pass >> >> if __name__ == '__main__': >> app = model.Application(Minimal) >> app.MainLoop() >> >> >> >> > def on_menuFileAbout_select(self, event): >> > >> > And, of course, if you replace the word "pass" with this, as >> > instructed: >> > >> > result = dialog.alertDialog(self, 'It works!', 'Showing Off') >> > >> > it won't run, because the existing "pass" line isn't inside a def >> > inside of a class. >> > >> >> No, it didn't work because the author forgot to mention that you have >> to do a: >> >> from PythonCard import model, dialog >> >> instead of just: >> >> from PythonCard import model >> >> I just tried it and it works. >> >> > >> > B) Is the Notebook widget really supported? >> > >> > In the installed file "changelog.txt" (gets installed as part of >> > PythonCard installation), it says: >> > >> > "added Notebook component, PageBackground, and testNotebook >> > sample" >> > >> > But, the testNotebook sample is nowhere to be found. >> > >> >> I haven't come across a need to use Notebook and so I can not say for >> sure. Looking at notebook.py, it appears to be just a simple wrapper >> on top of the wxWindow notebook. I would encourage you to post a >> message to the mailing list and ask there. >> >> >> > I looked lots of places, including the main SourceForge web site, >> > and on the wiki, here: >> > >> > http://wiki.wxpython.org/index.cgi/PythonCard >> > >> > Both the main website and the wiki seem way out of date, and the >> > latest dates I could find on both of them are sometime in 2004. >> > >> >> Yes, sometime around 2004, the website updating stopped. Fortunately, >> development didn't. There are quite a number of new things since then: >> new resource editor (now call layout Editor, standalone exe creator, >> and so forth). I even learn that a new sizer handler is in the work. >> >> Not saying that there are 10 programmers working 7/24 on it. It *is* >> an Open Source project nevertheless. Nobody gets paid for doing it. >> But there are development work going on. >> >> >> > Finally, by following the mailing list archive link on the main >> > website, I managed to find a reference to the notebook component on the >> > ASPN site, where some guy named Brian wonders about the same thing as >> > me, concerning the availability of the notebook component: >> > >> > http://aspn.activestate.com/ASPN/Mail/Message/pythoncard/2536825 >> > >> > and, that message led me here: >> > >> > http://article.gmane.org/gmane.comp.python.pythoncard/1060 >> > >> > where Kevin Altis admits that he forgot to include it in the 0.8.1 >> > release! At least he provides a way to download it separately. But, >> > gheesh, this is pretty poor for a new user. I was interested in using >> > the notebook component right away, because I looked at the wxGlade >> > tutorial before looking at PythonPage, and they use the notebook >> > component in their example (and I decided I really want to use the >> > component). >> > >> > To add insult to injury, after you download the zip file with the >> > testNotebook stuff, the readme file says this: >> > >> > "Until we have a Notebook integrated into some of the other >> > samples or tools this will serve as a basic test app, but I don't expect >> > to include it in releases." >> > >> >> >> As with all Open Source projects, your mileage differs. PythonCard >> does what *I* need to get done - and allowed me to get it done in a >> *hurry*. May be you really need Notebook and may be it's true that >> Notebook really doesn't work, I don't know. But if you managed to get >> it working, write it up and get it included. That's what Open Source >> Projects are all about. >> >> >> > C) Are the websites being maintained? >> >> >> It appears that the maintainer of the web site stopped updating it >> since late 2004. I don't know why. May be he's been busy. May be he >> got mad. I don't know. All I know is that I have been very >> productive with what I need to get done (and earned a happy living with >> the code I created) and I am very grateful to the people that worked on >> it - past and present. >> >> I am not a "professional programmer" and so I probably can't contribute >> to the development effort itself. However, I've gotten pretty good in >> using most of the package (other then Notebook, I admit). So, if you >> have any specific questions, please post it to the PythonCard list and >> I'll try to help if I can. >> >> Cheers. From duncan.booth at invalid.invalid Tue Nov 28 04:13:53 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Nov 2006 09:13:53 GMT Subject: Calling a thread asynchronously with a callback References: <4t0nr6F110supU1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > Edwin Gomez wrote: > >> I'm a C# developer and I'm new to Python. I would like to know if >> the concept of Asynchronous call-backs exists in Python. Basically >> what I mean is that I dispatch a thread and when the thread completes >> it invokes a method from the calling thread. Sort event driven >> concept with threads. > > Counter question: does such a thing exist in C#, and if, is it bound > to some existing event loop? Yes, or rather the concept exists in .Net. C# and other .Net languages don't actually allow pointers to functions, instead they implement callbacks using what are called Delegates: for each different function signature you need a new Delegate class, but the language compilers automate the process so that using Delegates becomes very similar to using function pointers. In early C#: // Delegate for function with no args and no results public delegate void SimpleDelegate(); ... SimpleDelegate simpleDelegate = new SimpleDelegate(somefunc); SimpleDelegate simpleDelegate = new SimpleDelegate(someobj.somefunc); ... simpleDelegate(); C# 2.0 added the ability to declare delegates inline (i.e. anonymous functions), and delegate inferencing to avoid writing 'new delegatename' everywhere: SimpleDelegate simpleDelegate = somefunc; Where delegates start becoming more interesting than just function pointers is that all delegates support both multicasting and asynchronous callbacks. You can add any number of functions into a delegate, and you can also remove functions from delegates. Asynchronous callbacks are done by calling a delegate's BeginInvoke method. You have to pass this the same arguments as you would when calling the delegate directly, plus an AsyncCallback delegate and an object to be passed as part of the asynchronous response which is usually the original delegate. From the callback you can then call EndInvoke to get the result returned from the call to the function. Now the bit you asked about: the callback happens on an arbitrary thread. The .Net runtime maintains a thread pool to use for this sort of callback so it doesn't have the overhead of setting up a new thread every time. A lot of the system library classes support similar Beginxxx/Endxxx function pairs for potentially lengthy operations such as reading from a Stream, or performing a web request and the thread pool is also used for these. It is fairly easy to implement a similar scheme in Python, just write a thread pool which gets function/argument/callback combinations from a queue, calls the function and then calls the callback with the response. > I'm really curious, because having code being interrupted at any time > by a asynchronous callback strikes me as dangerous. But then maybe I'm > just a whimp :) Not at all. It comes as a surprise to some people that there is no such thing in .Net as a single threaded program: As well as asynchronous delegates the garbage collector uses separate threads: what it does is to block all threads from running while it sweeps the memory, compacting all moveable objects and releasing any unreferenced objects without finalizers. Unreferenced objects with finalizers are resurrected onto a list and then the garbage collector lets other threads run. A background thread is then used to call the finalizers for the collected objects and each finalizer is cleared once it has executed (so that unless resurrected, the next garbage collection of an appropriate generation can overwrite the object). What this means is that *all* finalizers in .Net will run on a different thread (and in arbitrary order): of course finalizers are pretty crippled so this may not matter. From no-spam at no-spam-no-spam.invalid Wed Nov 8 11:18:12 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 08 Nov 2006 17:18:12 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <1162992063.382185.5440@h48g2000cwc.googlegroups.com> References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <7xk62ct5pf.fsf@ruckus.brouhaha.com> <1162913881.953664.254960@m73g2000cwd.googlegroups.com> <1162922230.992249.52430@f16g2000cwb.googlegroups.com> <4550cc64$0$3462$9b622d9e@news.freenet.de> <1162928970.223276.72600@h48g2000cwc.googlegroups.com> <4550F2AE.1010205@v.loewis.de> <1162939715.915139.146890@b28g2000cwb.googlegroups.com> <455166B6.6040009@v.loewis.de> <1162992063.382185.5440@h48g2000cwc.googlegroups.com> Message-ID: Ross Ridge wrote: > Ross Ridge schrieb: >> So give an example where reference counting is unsafe. > > Martin v. L?wis wrote: >> Nobody claimed that, in that thread. Instead, the claim was >> "Atomic increment and decrement instructions are not by themselves >> sufficient to make reference counting safe." > > So give an example of where atomic increment and decrement instructions > are not by themselves sufficent to make reference counting safe. > >> I did give an example, in <4550cc64$0$3462$9b622d9e at news.freenet.de>. >> Even though f_name is reference-counted, it might happen that you get a >> dangling pointer. > > Your example is of how access to the "f_name" member is unsafe, not of > how reference counting being unsafe. The same sort of race condition > can without reference counting being involved at all. Consider the > "f_fp" member: if one thread tries to use "printf()" on it while > another thread calls "fclose()", then you can have same problem. The > race condition here doesn't happen because reference counting hasn't > been made safe, nor does it happen because stdio isn't thread-safe. It > happens because accessing "f_fp" (without the GIL) is unsafe. > > The problem your describing isn't that reference counting hasn't been > made safe. What you and Joe seem to be trying to say is that atomic > increment and decrement instructions alone don't make accessing shared > structure members safe. Yes. To recall the motivation and have a real world example: The idea to share/handover objects between 2 (N) well separated Python interpreter instances (free-threading) with 2 different GILs. There is of course the usage condition: * Only one interpreter may access (read & write) the hot (tunneled) object tree at a time * (e.g. application: a numeric calc and when finished (flag) the other interpreter walks again the objects directly (without MPI/pickling)) But a key problem was, that the other thread can have old pointer objects (containers) pointing into the hot object tree - an there is shared use of (immutable) singleton objects (None,1,2...): The old pointer objects in other interpreter may disapear at any time or the pointers maybe be doubled. Thus the refcount of hot object will count down/up out of the interpreter which has not possession of the hot object tree - even if the pointers are not used for write/read access. Only and truly if you have atomic Py_INCREF/Py_DECREF this is no problem. Before all interpreters have lost the object there will be no accidental disapearance of the object as Ross Ridge already pointed out. In addition concurrent read access to _constant_ objects/sub-trees would be possible, and also concurrent read&write access by using an explicit locking! Thus the original OP requirements would be fulfilled. See so far only 5 main additional requirements to offer the possibility of separated GILs/free-threading interpreters: * pointer to current GIL in threadstate and dynamic PyThreadState_GET() / currentthreadstate in TLS * locks for global objects (file etc) of course, if they should be supported therefore. (I'd use the free-threading only for mere computations) * enable the already existing obmalloc.c/LOCK&UNLOCK by something fast like: _retry: __asm LOCK INC malloc_lock if (malloc_lock!=1) { LOCK DEC malloc_lock; /*yield();*/ goto _retry; } * a special (LOCK INC) locking dict type for the global dict of extension modules (created clearly by Py_InitModule(name, methods) - thus that would also preserve backwards compatibility for extension C-code) * nice tunnel functions to create extra interpreters and for actually tunneling the objects and maybe offering the fast locking-dict type to enable a fast sharing of the hot tunneled object tree. Speed costs? Probably not much as far as the discussion in this thread sounds... Of course this option of 2 interpreters - though easy to use - would still be for power use cases only: A Python programming bug doing accidential unlocked concurrent access into a hot tunneled tree can cause a C-level crash. (This cannot happen so far with simple Python threading - you'd only get inconsistent data or a Python exception. But of course you can crash already now at C-level by using the Python standard library :-) ). That danger would be ok for me so far. Conceptually its not more complicated that using locks right in normal Python thread programming - only the effect of bugs will more critical ... If one thinks about overcoming the GIL at all - we are probably not far away. Mainly: * make the locking dict type (and locking list type) the common case - the non-locking obsolete or for optimization only * lock some other non-constant types which are not already mainly dicts/lists. most objects which' access-functions only change INTEGERS etc and call threadsafe C-lib functions etc don't require extra locking Maybe the separated-GIL/interpreter-method can be a bridge to that. Refcounting probably doen't necessarily block that road. Really interesting would be to make an experiment about the speed costs of LOCK INC. Guess the hot spot regarding recounting will be Py_None's cache line (on multi core CPUs with separated cache per core). Robert From sjmachin at lexicon.net Tue Nov 21 20:16:28 2006 From: sjmachin at lexicon.net (John Machin) Date: 21 Nov 2006 17:16:28 -0800 Subject: AVL Balancing In-Reply-To: <1164154965.338691.327010@j44g2000cwa.googlegroups.com> References: <1164154965.338691.327010@j44g2000cwa.googlegroups.com> Message-ID: <1164158188.787394.25990@b28g2000cwb.googlegroups.com> scba... at gmail.com wrote: > Im working on an AVL tree Is this homework? > that consists of balancing the tree everytime > you add an object. That's a peculiar kind of AVL tree. Normally it is *not* necessary to balance the tree every time a node is added -- it's done only if a constraint is breached. > Im not quite grasping the concept on how to do this > with python. Could you do it in any other language? > I have seen a few topics on the web about this, and i > clearly understand how when the balance of an AVL tree get to 2 or -2 > you have to do a R, L, LR, or a RL rotation. Could anyone possibly help > me/point me in the right direction as far as checking the balance and > actually balancing the tree? Thanks in advance Perhaps if you could show us what you have done already -- I'd be expecting a class to represent a node, and maybe another to represent the root of the tree -- and give us an idea of your Python proficency level (so that we can tailor the advice accordingly), we could help you. Regards, John From gagsl-py at yahoo.com.ar Fri Nov 10 17:42:45 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 10 Nov 2006 19:42:45 -0300 Subject: newbee I have an object how to check what's his class? In-Reply-To: References: <1163171613.040825.78290@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20061110193222.0495a280@yahoo.com.ar> At Friday 10/11/2006 18:05, consternation wrote: >def __init__ > self.mem={} >I googled a way how to add elements to dict, I have read the code not the >description below self.mem[key] = value I strongly suggest you read some introductory Python docs, like http://docs.python.org/tut/tut.html or http://www.diveintopython.org >isinstance(x,X) >True :-) >type(x) is X >False :( ?? >__main__.X >X > temporarily it solves my probblems I'm just curious why type can't handle >the test. You still didn't show enough code, but I bet that X is an old-style class, that is, you wrote: class X: blablabla instead of class X(object): blablabla For old-style class instances, type(x) is InstanceType, not the actual class. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From cyberco at gmail.com Mon Nov 20 03:26:14 2006 From: cyberco at gmail.com (cyberco) Date: 20 Nov 2006 00:26:14 -0800 Subject: fileinput.input('test.txt') => ERROR: input() already active Message-ID: <1164011174.630226.91580@j44g2000cwa.googlegroups.com> Using fileinput.input('test.txt') I probably forgot to process all lines or so, since I get the error 'input() already active' when i try to call fileinput.input('test.txt') again. But how can I 'close' the previous version I opened? I have no handle to it or so... From ardsrk at gmail.com Sat Nov 4 07:57:51 2006 From: ardsrk at gmail.com (ArdPy) Date: 4 Nov 2006 04:57:51 -0800 Subject: Really strange behavior In-Reply-To: References: Message-ID: <1162645071.162131.194070@h48g2000cwc.googlegroups.com> IloChab wrote: > Sorry I wasn't able to be more specific on my topic but I really do not > know how to classify my problem, I mean that I can't understand if it's > a python > or a twisted > or a Qt4 > problem > I'm trying to run a simple application with Twisted and Qt4. > To do this I downloaded this: > http://twistedmatrix.com/trac/attachment/ticket/1770/qt4reactor.py > Now, > if I run this: > # >>>>>>>>> > import qt4reactor > import sys > from PyQt4 import QtGui > from winIum import Window > > def main(): > app = QtGui.QApplication(sys.argv) > qt4reactor.install(app) > MainWindow = QtGui.QMainWindow() > win = Window(MainWindow) > MainWindow.show() > from twisted.internet import reactor > reactor.run() > # <<<<<<<< > my window shows and run correctly. > > If I run this: > # >>>>>>>>>>>>> > import qt4reactor > import sys > from PyQt4 import QtGui > from winIum import Window > > def creApp(): > app = QtGui.QApplication(sys.argv) > qt4reactor.install(app) > retrun app > def creWin(): > MainWindow = QtGui.QMainWindow() > win = Window(MainWindow) > MainWindow.show() > def main(): > app = creApp() > creWin() > from twisted.internet import reactor > reactor.run() > # <<<<<<<<<<<<< > my window doesn't show and the script doesn't stop but remains trapped in > some gui loop. > > What's the problem I can't see?? > > Thank you in advance for any help. > Licia Well the only problem according to me could be with the 'from twisted.internet import reactor' statement. Try putting this at the beginning of the script. Might be it will work just fine... From Thomas.Ploch at gmx.net Thu Nov 30 15:34:11 2006 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Thu, 30 Nov 2006 21:34:11 +0100 Subject: Is there an easier way to express this list slicing? In-Reply-To: <1164917869.978435.63370@f1g2000cwa.googlegroups.com> References: <1164913125.509492.54060@79g2000cws.googlegroups.com> <1164917869.978435.63370@f1g2000cwa.googlegroups.com> Message-ID: <456F4043.2060208@gmx.net> John Henry schrieb: > Thomas Ploch wrote: > >> I had a little bit of fun while writing this: >> >> itemList = (a,b,c1,c2,c3,d1,d2,d3,d4,d5) and >> itemList2 = (a1,a2,a3,b,c,d1,d2,d3,d4,d5) the next time. >> > > Huh? What's a,b,....d5? > John Henry schrieb: > > Thomas Ploch wrote: > > >> >> I had a little bit of fun while writing this: >> >> >> >> itemList = (a,b,c1,c2,c3,d1,d2,d3,d4,d5) and >> >> itemList2 = (a1,a2,a3,b,c,d1,d2,d3,d4,d5) the next time. >> >> > > > > Huh? What's a,b,....d5? > > Can be any object, as you had in your example in your mail: >>>If I have a list of say, 10 elements and I need to slice it into >>> irregular size list, I would have to create a bunch of temporary >>> variables and then regroup them afterwords, like: >>> >>> # Just for illustration. Alist can be any existing 10 element list >>> a_list=("",)*10 >>> (a,b,c1,c2,c3,d1,d2,d3,d4,d5)=a_list >>> alist=(a,) >>> blist=(b,) >>> clist=(c1,c2,c3) >>> dlist=(d2,d3,d4,d5) >> def getSlices(aCount, bCount, cCount, dCount, items): >> a,b,c,d = (items[0:aCount], >> items[aCount:aCount+bCount], >> items[aCount+bCount:aCount+bCount+cCount], >> item[aCount+bCount+cCount:aCount+bCount+cCount+dCount]) > > You meant "items" here, right? > >> return list(a),list(b),list(c),list(d) >> >>>>> a,b,c,d = getSlices(1,1,3,5,itemList) >>>>> print a,b,c,d >> ['a'] ['b'] ['c1', 'c2', 'c3'] ['d1', 'd2', 'd3', 'd4', 'd5'] >> >>>>> a,b,c,d = getSlices(3,1,1,0,itemList2) >>>>> print a,b,c,d >> ['a1', 'a2', 'a3'] ['b'] ['c'] [] >> >> %-) >> >> Thomas > From bearophileHUGS at lycos.com Thu Nov 2 02:09:39 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Nov 2006 23:09:39 -0800 Subject: Style for modules with lots of constants In-Reply-To: References: <1162398506.919161.145290@m7g2000cwm.googlegroups.com> Message-ID: <1162451379.767949.107720@h48g2000cwc.googlegroups.com> Ron Adam: > The disadvantage is an invalid flag may pass silently unless you do some sort of > validation which may slow things down a bit. That string validation is usually necessary. Bye, bearophile From brenNOSPAMbarn at NObrenSPAMbarn.net Mon Nov 27 23:12:39 2006 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Tue, 28 Nov 2006 04:12:39 GMT Subject: Inheritance from builtin list and override of methods. References: <200611261804.54669.mgiann@beta-cae.gr> <200611271133.48359.mgiann@beta-cae.gr> Message-ID: Carsten Haese wrote: > You can change the behavior of a list's sort method by overriding > sort. You can't change the behavior of sort by overriding > __getitem__ and __setitem__, because sort does not call __getitem__ > or __setitem__. Why doesn't it? -- --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 jblaine at mitre.org Wed Nov 1 15:57:23 2006 From: jblaine at mitre.org (Jeff Blaine) Date: Wed, 01 Nov 2006 15:57:23 -0500 Subject: CSV module, DictReader problem (bug?) In-Reply-To: References: Message-ID: I see what's wrong. Me. Wow am I ever rusty. Jeff Blaine wrote: > It's been a year or so since I written Python code, so maybe > I am just doing something really dumb, but... > > Documentation > ============= > > class DictReader(csvfile[,fieldnames=None, > [,restkey=None[, restval=None[, dialect='excel' > [, *args, **kwds]]]]]) > > > Create an object which operates like a regular reader > but maps the information read into a dict whose keys > are given by the optional fieldnames parameter. If the > fieldnames parameter is omitted, the values in the > first row of the csvfile will be used as the fieldnames. > > Code > ==== > > import csv > > r = csv.DictReader('C:\Temp\Book1.csv') > print r.next() > # EOF > > Output > ====== > > {'C': ':'} From klaus at seistrup.dk Tue Nov 21 14:23:36 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Tue, 21 Nov 2006 19:23:36 +0000 (UTC) Subject: How to sort list References: <1164136547.137154.126740@m73g2000cwd.googlegroups.com> Message-ID: Lad wrote: > I have a list of emails and I would like to sorted that list by > domains > E.g. > If the list is > > Emails=['a at hotmail.com','a at yahoo.com','b at hotmail.com','c at yahoo.com',....] > > after sorting I would like to have > Emails=['a at hotmail.com','b at hotmail.com','a at yahoo.com','c at yahoo.com',....] > > What is the best/easiest way? Decorate-sort-undecorate? #v+ array = [] for addr in Emails: (user, domain) = addr.split('@') array.append((domain, user, addr)) # end for array.sort() SortedEmails = [addr for (user, domain, addr) in array] #v- Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From gagsl-py at yahoo.com.ar Wed Nov 29 03:06:25 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 29 Nov 2006 05:06:25 -0300 Subject: Using SimpleXMLRPCServer in a Windows Service In-Reply-To: <60987dac0611280049t4138334r13ddbfb7c7236b5b@mail.gmail.com > References: <60987dac0611230152r4af42ce6mfbbaf5a4409537ee@mail.gmail.com> <7.0.1.0.0.20061125003821.034c9810@yahoo.com.ar> <60987dac0611280049t4138334r13ddbfb7c7236b5b@mail.gmail.com> Message-ID: <7.0.1.0.0.20061129050330.04d37770@yahoo.com.ar> At Tuesday 28/11/2006 05:49, Rudy Schockaert wrote: >I found the problem. >Actually both pieces of code work now. The problem was that when I run >the SimpleXMLRPCService in a Windows Service, the STDERR needs to be >redirected to a real file. I guess some kind of buffer overflow occurs >when you don't do this. > >I added the following lines: > > >def SvcStop(self): > sys.stdout = self.stdout > sys.stderr = self.stderr > ..... > > >def SvcDoRun(self): > self.stdout = sys.stdout > self.stderr = sys.stderr > sys.stdout = file("c:/temp/my.log", "a+", 0) > sys.stderr = sys.stderr > .... > Actually you don't have to restore the previous value; Python already saves the original value in sys.__stderr__ and restores it when program finishes. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From duncan.booth at invalid.invalid Thu Nov 30 08:09:11 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Nov 2006 13:09:11 GMT Subject: Slicing versus loops, was Re: for i in range() anti-pattern References: <1164812827.653386.323320@80g2000cwy.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Everybody always forgets corner cases... like lists with odd number of > items... *wink* > I didn't forget. I just assumed that raising an exception was a more useful response. > Here is a version that handles both odd and even length lists: > > def swap_slice(items): > left = items[:len(items)-1:2] > items[:len(items)-1:2] = items[1::2] > items[1::2] = left > return items > I guess a viable alternative to raising an exception would be to pad the list to even length: [1, 2, 3] -> [2, 1, Padding, 3] for some value of Padding. I don't think I would expect swap_slice to silently fail to swap the last element. From ytlim1 at gmail.com Sat Nov 18 16:44:27 2006 From: ytlim1 at gmail.com (Why Tea) Date: 18 Nov 2006 13:44:27 -0800 Subject: print with variable justification (with *) In-Reply-To: References: <1163883589.401180.271190@m73g2000cwd.googlegroups.com> Message-ID: <1163886267.733427.108740@j44g2000cwa.googlegroups.com> > In [50]: '%*s' % (5, 'spam') > Out[50]: ' spam' > Marc, that's exactly what I need. Thanks! /Why Tea From xah at xahlee.org Wed Nov 1 05:35:08 2006 From: xah at xahlee.org (Xah Lee) Date: 1 Nov 2006 02:35:08 -0800 Subject: logo design In-Reply-To: <1162270625.966859.194730@m73g2000cwd.googlegroups.com> References: <1162103065.460796.303660@f16g2000cwb.googlegroups.com> <1162270625.966859.194730@m73g2000cwd.googlegroups.com> Message-ID: <1162377308.044332.212610@i42g2000cwa.googlegroups.com> No personal offense intended, but human animal's history is what? 3000 years at least in recorded history? And, all you can think of is what, the view points of a fraction of your personal life span? Have you looked into, the history of fashions, icons, their roles and social significance, before you embarked and embraced on your above-it attitude about why should or should not your pet language lisp have a logo? As per more detailed reasons on the meaning of logos, it's social significance, its role in modern society, the defining characteristics of logo design, and why LISP needs a logo, i'll post a reply to this thread wthin a month. Xah xah at xahlee.org ? http://xahlee.org/ mark.hoemmen at gmail.com wrote: > On Oct 28, 10:24 pm, "Xah Lee" wrote: > > I have brought this topic here here before... that i think LISP really > > need to have a logo. > > No offense intended, but were you around in 1959 or so? The way > that time passes in the computer science world, having a logo for > Lisp is like having a logo for the abacus ;) Besides, who are _we_ > to go back and impose our modern ideas of what looks "slick" and > pretty on the great thinkers of an earlier age? Should we make a > logo for the Pythagorean Theorem or for Newton's Three Laws? > > > Python, did not really have a logo. I made a plaint more than once in > > different periods of times to comp.lang.python. Them tech geeking > > morons and assholes, as expected, made irrelevant and incoherent cries. > > I personally have a lot of respect for Python hackers and I think > you should too. We Lispers should show our greatness by not > stooping to such insults ;) > > mfh From bugs at almad.net Mon Nov 6 05:04:12 2006 From: bugs at almad.net (Almad) Date: 6 Nov 2006 02:04:12 -0800 Subject: Problem with XML-RPC not mounted in / Message-ID: <1162807451.890014.307850@k70g2000cwa.googlegroups.com> Hi, I'm trying to build XML-RPC service, both server and client library. My server is CherryPy with XML-RPC filter. I have here method registration_ip. When it's in, say http://ws.rpgplanet.nerv/, everything is OK, but when I move it in http://ws.rpgplanet.nerv/main/, this behaviour occur: srv = ServerProxy('http://ws.rpgplanet.nerv/main/') print srv.register_ip("guest") raises 404, as according to log, library is trying to access /main/ instead of /main/register_ip srv = ServerProxy('http://ws.rpgplanet.nerv/') print srv.main.register_ip("guest") raises 500, as client is correctly hitting /main/register_ip, but NOT sending "guest" argument. I'm probably missing something obvious, so where should problem be? Is it not possible for XML-RPC to live not in / ? Thank You for advices, Almad From bignose+hates-spam at benfinney.id.au Thu Nov 23 23:34:16 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 24 Nov 2006 15:34:16 +1100 Subject: beginner question about range with list and list References: <1164341231.638722.134130@m7g2000cwm.googlegroups.com> Message-ID: <87vel5tqd3.fsf@benfinney.id.au> "erik gartz" writes: > Doesn't {} allocate new memory for the dictionary each time? It > almost appears as if the 2nd dictionary created overwrites the first > one. -- \ "There are only two ways to live your life. One is as though | `\ nothing is a miracle. The other is as if everything is." -- | _o__) Albert Einstein | Ben Finney From walterbyrd at iname.com Thu Nov 2 21:06:26 2006 From: walterbyrd at iname.com (walterbyrd) Date: 2 Nov 2006 18:06:26 -0800 Subject: is mod_python borked? In-Reply-To: <1162509979.221261.192440@m7g2000cwm.googlegroups.com> References: <1162480110.992783.267620@e3g2000cwe.googlegroups.com> <1162509979.221261.192440@m7g2000cwm.googlegroups.com> Message-ID: <1162519586.681243.301550@h48g2000cwc.googlegroups.com> grahamd at dscpl.com.au wrote: > One of the biggest problems is that a lot of ISPs still use Apache 1.3 > and so only mod_python 2.7.X is available on those platforms. Yes, I think that is a big problem. I don't think django or turbogears will work with apache 1.3. And it seems to me that practically all web-hosters use apache 1.3. *sigh* maybe I'll just use php until the web-hosters catch up, if they ever do. From nicogrubert at gmail.com Thu Nov 23 09:05:14 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 23 Nov 2006 15:05:14 +0100 Subject: ldapsearch example in python-ldap? Message-ID: <4565AA9A.5050902@gmail.com> Hi there, on a linux machine I am running this ldapsearch from the command line: ldapsearch -x -h myldaphost.mydomain.com \ -D "CN=ldapuser,CN=Users,DC=mydomain,DC=com" -w "secret" \ -b "CN=ANYCOMPUTER,CN=Computers,DC=mydomain,DC=com" How can I do this with python-ldap? Regards, Nico From cameron.walsh at gmail.com Thu Nov 30 20:42:41 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Fri, 01 Dec 2006 09:42:41 +0800 Subject: PIL throws exception when reading bitmap/pnm data In-Reply-To: References: Message-ID: Cameron Walsh wrote: > Hi all, > > I'm trying to extract the data from a bitmap or .pnm file using the > following code: > > import Image > img = Image.open("test.bmp","r") > data=img.getdata() > > Unfortunately I get the following exception on Linux, but not on Windows: > >>>> data=img.getdata() > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python2.5/site-packages/PIL/Image.py", line 796, > in getdata > self.load() > File "/usr/local/lib/python2.5/site-packages/PIL/ImageFile.py", line > 147, in load > self.map = mmap.mmap(file.fileno(), size) > EnvironmentError: [Errno 19] No such device > > > > Thanks and regards, > > Cameron. Hi all, It turns out the problem only arose when the file was on an NTFS drive mounted as NTFS-3g. Copying it to my home directory fixed the problem. Who do I send the bug report to, the ntfs-3g or the PIL guys? Regards, Cameron. From walterbyrd at iname.com Tue Nov 14 14:38:46 2006 From: walterbyrd at iname.com (walterbyrd) Date: 14 Nov 2006 11:38:46 -0800 Subject: Python v PHP: fair comparison? Message-ID: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> I don't know if this is a fair comparison or not. Any comments appreciated. - Python is more readable, and more general purpose - PHP has awful backward compatibility - PHP has a lower barrier to entry - Most inexpensive web-hosters support PHP, but not Python - PHP has far more pre-writen scripts available - Newer versions of mod_python require Apache 2.0, which few hosters have - There is more demand for PHP developers, than Python developers From Leo.Kislov at gmail.com Tue Nov 28 06:45:59 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 28 Nov 2006 03:45:59 -0800 Subject: os.walk return hex excapes References: Message-ID: <1164714359.370358.316870@j72g2000cwa.googlegroups.com> Alex S wrote: > Hi, > os.walk return hex excape sequence inside a files name, and when i try > to feed it back to os.remove i get > > OSError: [Errno 22] Invalid argument: > 'C:\\Temp\\?p?\xbfS\xbf\xac?G\xaba ACDSee \xbb?a??n a???\xac\xb5\xbfn.exe' It's not escape sequences that are the problem but question marks, I suspect. Most likely this file name contains characters not in your locale's language. To access this file name you need to use unicode, just make sure the first parameter of os.walk is a unicode string, for example: os.walk(u'c:\\temp'). The exact code how to make the first parameter unicode depends on where it is coming from (network, config file, registry, etc...) Reading unicode tutorial is highly recommended. -- Leo From jcoleman at franciscan.edu Thu Nov 2 16:56:42 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 2 Nov 2006 13:56:42 -0800 Subject: Python in sci/tech applications In-Reply-To: References: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> <1162489638.013433.102180@h48g2000cwc.googlegroups.com> <1162491753.605134.162700@i42g2000cwa.googlegroups.com> <1162502997.175322.171730@e3g2000cwe.googlegroups.com> Message-ID: <1162504602.877056.114150@h48g2000cwc.googlegroups.com> Robert Kern wrote: > John Coleman wrote: > > Maybe I don't know what I'm looking for, but I downloaded Enthought a > > few days ago and don't seem to find MinGW on my system. There are 2 > > relatively small (totalling about 13 kb IIRC) *python* files deeply > > buried in the distribution with mingw in their filename but nothing > > like a gcc compiler. I've mostly used visual studio or code warrior for > > C compiling, so again - maybe I don't know what I am looking for. > > It is in c:\Python24\Enthought\mingw32\, IIRC (I don't have it in front of me). > Add c:\Python24\Enthought\mingw32\bin\ to your PATH environment variable, and > gcc.exe should be executable. > I have no such sub-directory. I'll try an uninstall-install. When I did the original installation the installer hung at the end and I had to manually close it. The Python interpreter was there and worked properly and all of the goodies like numby and chaco were there so I wrote it off as nothing more then a failure to close properly, but evidently I missed an essential part of the installation. -John Coleman > -- > 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 R.Brodie at rl.ac.uk Thu Nov 23 06:12:56 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 23 Nov 2006 11:12:56 -0000 Subject: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]? References: Message-ID: "Tor Erik Soenvisen" wrote in message news:Xns9884782092A96toreriknpolarno at 129.242.5.222... > which executes fine. Hence, 0-9999 is okey... But this is a relatively > small range, and sooner or later you probably get two numbers with the same > id... Thoughts anyone? I think you are confusing yourself unnecessarily. The obvious way to implement unique ids is to return the address of the object. It's very unlikely that two different objects share the same address. From aaghamarshana at gmail.com Wed Nov 29 04:48:06 2006 From: aaghamarshana at gmail.com (B Shyam Sundar) Date: Wed, 29 Nov 2006 01:48:06 -0800 Subject: Small prog question from a newbie: abt variables in a function definition Message-ID: Hi all, I am a newbie as far as python is concerned ... I am trying to write a code for playing bridge in obj oriented manner .. Well ... i have this small problem: class hand: def __init__(self,set_of_cards=[]): self.set_of_cards=set_of_cards card_played_flag =0 def play(played_card): for i in self.set_of_cards: if self.set_of_cards[i] == played_card: self.set_of_cards.remove(played_card) def sort_hand(): for i in self.set_of_cards: for j in self.set_of_cards: if self.set_of_cards[j].face From fredrik at pythonware.com Thu Nov 2 08:28:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 02 Nov 2006 14:28:45 +0100 Subject: other ways to check for ? In-Reply-To: <1162473318.495571.55550@h54g2000cwb.googlegroups.com> References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> <1162473318.495571.55550@h54g2000cwb.googlegroups.com> Message-ID: John Roth wrote: > PEP 3100 specifies that the callable builtin is > to be removed in Python 3.0, together with what > I presume is the underlying C support for the > function. PEP 3100 is not even close to being finalized, and does not apply to Python 2.X. From aisaac at american.edu Sat Nov 11 08:10:54 2006 From: aisaac at american.edu (Alan Isaac) Date: Sat, 11 Nov 2006 13:10:54 GMT Subject: handling many default values References: Message-ID: > At Friday 10/11/2006 14:11, Alan G Isaac wrote: > >class Params: > > def __init__(self,**kwargs): > > #set lots of default values > > ... > > #set the deviations from defaults > > self.__dict__.update(kwargs) > > > >Is this a reasonable approach overall? > >(Including the last line.) "Gabriel Genellina" wrote in message news:mailman.2074.1163201795.11739.python-list at python.org... > I'm not sure what you want to do exactly, but a class attribute acts > as a default instance attribute. Yes. I am sorry my question was not clearer. There are *many* parameters, and the list can change, so I want to avoid listing them all in the Param class's __init__ function, using the strategy above. Q1: Is this approach reasonable? (This is a newbie question about unforseen hazards.) Q2: Is it horrible design to isolate the parameters in a separate class? (Comment: currently several classes may rely on (parts of) the same parameter set.) Thanks, Alan Isaac From NikitaTheSpider at gmail.com Tue Nov 21 14:56:11 2006 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Tue, 21 Nov 2006 19:56:11 GMT Subject: Spyce system requirements? References: <1164127246.887153.98820@m7g2000cwm.googlegroups.com> Message-ID: In article <1164127246.887153.98820 at m7g2000cwm.googlegroups.com>, "walterbyrd" wrote: > Does anybody know? What versionof Apache is required? If used with > mod_python, what version of mod_python? Why version of Python is > required? > > Any help appreciated, thanx. >From the Spyce documentation: "Python version 2.3 or greater. Spyce uses no version-specific Apache features." http://spyce.sourceforge.net/docs/doc-conf_overview.html There's also a Spyce mailing list your questions aren't answered in the documentation. -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From mail at microcorp.co.za Tue Nov 14 01:23:03 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 14 Nov 2006 08:23:03 +0200 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com><4rhku3FriokeU2@mid.individual.net><4rjlkqFrlskqU1@mid.individual.net><4rk5giFrerjfU1@mid.individual.net> <022001c7055a$b24c7860$03000080@hendrik> <8c7f10c60611130605i382312c4l829d6167ae0a5828@mail.gmail.com> Message-ID: <02d901c707c2$82410ea0$03000080@hendrik> "Simon Brunning" Wrote: > On 11/11/06, Fredrik Lundh wrote: > > Hendrik van Rooyen wrote: > > > > >> blue is red or green or yellow > > > > > > *grin* - this can be construed as a weakness in Python - > > > > it's boolean logic, and it's incompatible with human use of the same > > terms in all contexts, not just Python. > > Indeed. > > The other day, I way showing my eight year old, Freja, what a program > looks like: > > your_name = raw_input("What's your name? ") > if your_name.lower() == "freja": > print "You're very stinky,", your_name > else: > print "You smell lovely, ", your_name > > After running it a couple of times, she dove in and changed the 2nd line to: > > if your_name.lower() == "daddy or ella": > > (Ella is my other daughter's name.) That's pretty close to correct, > I'd say - but you don't get anything for being close in a programming > language. This is true - and it is actually also an intractable problem - if you look at what your daughter wrote, you get the feeling that you should be able to write an interpreter that can implement what she meant, because it is quite clear to you - until you try to write the specs... Your daughter, btw, will go far if she already has the guts to do that... - Hendrik From __peter__ at web.de Thu Nov 9 12:56:55 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Nov 2006 18:56:55 +0100 Subject: __div__ not recognized automatically References: Message-ID: Anton81 wrote: >> If you have the >> >> from __future__ import division >> >> statement, you need to override __truediv__(), not __div__() > > That worked after I also added > from __future__ import division > to all other modules I created. > > Is it possible that there appears an inconsistency if the division is > imported in only some of the modules? Yes. If you use your class with and without the __future__ option you have to implement both __div__ and __truediv__, I suppose. Peter From hollowspook at gmail.com Sun Nov 26 03:25:13 2006 From: hollowspook at gmail.com (hollowspook) Date: 26 Nov 2006 00:25:13 -0800 Subject: problem about list indexing Message-ID: <1164529513.862598.221550@h54g2000cwb.googlegroups.com> Hi, there a = range(100) if I want to use No 7, 11, 56,90 in a, then the only way I do is [a[7], a[11], a[56], a[90]]. Is there any other way? Thanks in advance. From fredrik at pythonware.com Sat Nov 11 17:23:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 11 Nov 2006 23:23:27 +0100 Subject: explicit self revisited In-Reply-To: References: Message-ID: > cannot all you clueless trolls who cannot think of a single useful thing > to contribute to Python start your own newsgroup? and before anyone complains; please note that they're working through http://www.effbot.org/pyfaq/design-index.htm one article at a time. who's going to be the first one to argue that Python needs a goto statement ? From rpdooling at gmail.com Tue Nov 7 16:55:00 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 7 Nov 2006 13:55:00 -0800 Subject: Tired of spam, unrelated email? In-Reply-To: References: <000601c7029a$7b0a7310$6400a8c0@genesis> Message-ID: <1162936500.037583.267680@b28g2000cwb.googlegroups.com> Steven D'Aprano wrote: > Due to the vagaries of Usenet, > I never received the original piece of spam > at all Same here. I do all of my persuing via Google Groups, and sometimes the same thing happens in a legitimate thread. I see somebody responding as the fist message in the thread, but I never see the OP. Odd. rd From bjobrien62 at gmail.com Thu Nov 2 17:23:47 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 2 Nov 2006 14:23:47 -0800 Subject: scared about refrences... In-Reply-To: <454a5672$0$3721$426a74cc@news.free.fr> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162251429.386255.289620@e3g2000cwe.googlegroups.com> <4547d0d7$0$7246$426a34cc@news.free.fr> <1162412436.595926.66940@i42g2000cwa.googlegroups.com> <454a5672$0$3721$426a74cc@news.free.fr> Message-ID: <1162506227.070059.230550@h54g2000cwb.googlegroups.com> Bruno Desthuilliers wrote: > SpreadTooThin a ?crit : > > Bruno Desthuilliers wrote: > > > >>Nick Vatamaniuc a ?crit : > >>(snip) > >> > >>>In Python all the primitives are copied and all other entities are > >>>references. > >> > >>Plain wrong. There's no "primitives" (ie : primitive data types) in > >>Python, only objects. And they all get passed the same way. > > > > > > so.. > > def fn(x): > > x = x + 1 > > print x > > > > a = 2 > > fn(a) > > fn(2) > > > > Wouldn't you say that this is being passed by value rather than by > > refrence? > > It's not passed by value. when in fn(), the *local* name 'x' is bound to > (IOW:references) the exact same object you passed to fn(). Then you > rebind this (local) name to *another* object. > > def fn((x): > print id(x) > x = x + 1 > print id(x) > > n = 1256 > print id(n) > fn(n) > > def fn2(alist): > print id(alist) > alist.append(42) > > mylist = [] > print id(mylist) > fn2(mylist) > print mylist > print id(mylist) > > > There's nothing like "pass by value" or "pass by reference" in Python > (and you'll notice I didn't claimed anything about this - just that the > 'argument passing scheme' was the same for all objects). > > What we call "variables" in Python are name=>object bindings. When > passing a "variable" to a function, the reference to the objet is bound > to the name of the argument in the function's namespace. So the *name* > is local to the function (hence rebinding the name to another objet > doesn't impact the name=>object binding in the caller's namespace), but > this name really refers to the same object (Python doesn't copy anything > unless explicitely told to do so). > > HTH I realize I may be beating a dead horse here... but... a = 2 fn(a) >>> 3 print a >>> 2 So in some cases the it is safe to assume that your variables to function will not change in other cases it is not.. but they are all the same... From steve at REMOVE.THIS.cybersource.com.au Sun Nov 12 17:33:06 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 13 Nov 2006 09:33:06 +1100 Subject: Random image text generation? References: Message-ID: On Sun, 12 Nov 2006 14:56:49 -0600, skip wrote: > > >> Is there a module out there that will generate an image with a random > >> text string such as the confirmation images you see on various > >> websites? > > Mitja> They're called captcha images or captchas for short. Googling > Mitja> for "python captcha" returns several hits; see what you like... > > Thanks. I'd never heard that term before. Assuming I can get PIL installed > with freetype support on my Mac the ASPN recipe looks like it will do the > trick. Keep in mind two serious problems with captchas: - they're impossible for the blind or people using text-only browsers to see -- even mere colour blindness can make some captchas impossible to solve; - sometimes they're too difficult for even those with perfect vision to decipher. Two alternatives: Instead of displaying an obfuscated image of a nonsense word, display six randomly chosen photos, where five are of the same thing but not the same image. E.g. you might show five different kittens and a horse. The user has to click on the image that is not the same as the others. State-of-the-art horse-recognition software is not yet in widespread use by spammers *wink* For a text only solution, consider putting up a natural language question such as: What is the third letter of 'national'? What is four plus two? How many eggs in a dozen? Fill in the blank: Mary had a little ____ its fleece was white as snow. Cat, Dog, Apple, Bird. One of those words is a fruit. Which one? Beware of making the questions too difficult or too specific: In the third season of Babylon Five, what did Mr Morden ask Lando? Also, keep in mind that all captchas are vulnerable to the old distributed hybrid human-machine network trick: "We'll give you a free account on our porn site if you spend fifteen minutes a day solving captchas for our bot network." The only solution to that, I fear, is open season on spammers and anyone who buys from a spammer. -- Steven. From cemerick at snowtide.com Thu Nov 16 07:58:38 2006 From: cemerick at snowtide.com (Chas Emerick) Date: Thu, 16 Nov 2006 07:58:38 -0500 Subject: lxml/ElementTree and .tail In-Reply-To: References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> <761846B7-E374-41FE-8804-CBB3D42FD4D2@snowtide.com> Message-ID: On Nov 16, 2006, at 7:25 AM, Fredrik Lundh wrote: >> If I'm wrong, just chalk it up to the fact that this is the first >> time I've ever looked at the Infoset spec, and I'm simply confused. > > the Infoset spec *is* the essence of XML; if you don't realize that an > XML document is just a serialization of a very simple data model, > you're > bound to be fighting with XML all the time. The principle and the practice diverge significantly in our neck of the woods. The current project involves consuming and making sense of extraordinarily (and typically unnecessarily) complex XHTML. Of course, as you say, those documents are still serializations of a simple data model, but the types of manipulations we do happen to butt up very uncomfortably with the way ET does things. > but ET doesn't implement the Infoset spec as it is, of course: it > uses a > *simplified* model, carefully optimized for the large percentage of > all > XML formats that simply doesn't use mixed content. if you're doing > document-style processing, you sometimes need to add an extra > assignment > or two, but unless you're doing *only* document-style processing, ET's > API gives you a net win. (and even if you're doing only document- > style > processing, ET's speed and memory footprint gives you a net win over > most competing technologies). Yeah, documents are all we do -- XML just happens to be a pleasant intermediate format, and something we need to consume. The notion of an nicely-formatted XML is entirely foreign to the work that we do -- in fact, our current focus is (in part) dragging decidedly unstructured data out of those XHTML documents (among other source formats) and putting them into a reasonable, useful structure. I took some time last night to bang out some functions that squeezed ET's model (via lxml) into doing what we need, and it ended up requiring a lot more B&D than I like. At that point, I swung over to 4suite, which dropped into place quite nicely. *shrug* I guess we're just in the minority with regard to our API requirements -- we happen to live in the corner cases. I'm certainly glad to have made the detour on a different path for a bit though. - Chas From lisa.engblom at gmail.com Wed Nov 29 11:18:59 2006 From: lisa.engblom at gmail.com (lisa.engblom at gmail.com) Date: 29 Nov 2006 08:18:59 -0800 Subject: trouble writing results to files In-Reply-To: References: <1164812827.653386.323320@80g2000cwy.googlegroups.com> Message-ID: <1164817139.688429.120410@14g2000cws.googlegroups.com> Roberto Bonvallet wrote: > lisa.engblom at gmail.com wrote: > > import csv > > output = csv.writer(open('/Python25/working/output.csv', 'a')) > > a = ["apple", "cranberry", "tart"] > > for elem in range(len(a)): > > output.writerow(a[elem]) > > output.writerow expects a sequence as an argument. You are passing a > string, which is a sequence of characters. By the way, what output are you > expecting to get? Do you want a file with only one line (apple, > cranberry, tart), or each fruit in a different line? I want it to print everything on one line and then create a new line where it will print some more stuff. In my real program I am iterating and it will eventually print the list a couple hundred times. But it would be useful to understand how to tell it to do either. > BTW, iterating over range(len(a)) is an anti-pattern in Python. You should > do it like this: > > for item in a: > output.writerow([item]) I can try that. Is using range(len(a)) a bad solution in the sense that its likely to create an unexpected error? Or because there is a more efficient way to accomplish the same thing? thanks! Lisa From tim at tdw.net Wed Nov 8 19:00:04 2006 From: tim at tdw.net (Tim Williams) Date: Thu, 9 Nov 2006 00:00:04 +0000 Subject: Python to tell what is the IP of my PC . In-Reply-To: References: Message-ID: <9afea2ac0611081600r7b2deb49pde0a6477bab7c7ca@mail.gmail.com> On 8 Nov 2006 15:35:31 -0800, NicolasG wrote: > How can I use python to get the real IP address of my DSL router (when > my PC is part of the local home LAN) ? The router will the PC's default gateway IP address, if you are on a windows platform, you can view it by typing IPCONFIG (enter) from a command prompt. A quick google, gave me this, look at the comments at the end for an example of finding the Default Gateway IP address using Python http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/162994 HTH :) From fredrik at pythonware.com Fri Nov 17 01:53:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 17 Nov 2006 07:53:39 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: References: Message-ID: gabor wrote: > get an Unicode-exception, as everywhere else. you see, exceptions are > ok, i can deal with them. > p.s: one additional note. if you code expects os.listdir to return > unicode, that usually means that all your code uses unicode strings. > which in turn means, that those filenames will somehow later interact > with unicode strings. which means that that byte-string-filename will > probably get auto-converted to unicode at a later point, and that > auto-conversion will VERY probably fail it will raise an exception, most likely. didn't you just say that exceptions were ok? From onemoverx at gmail.com Fri Nov 10 20:37:36 2006 From: onemoverx at gmail.com (=?ISO-8859-1?Q?Yusnel_Rojas_Garc=EDa?=) Date: Fri, 10 Nov 2006 20:37:36 -0500 Subject: wsdl question Message-ID: <9f45496e0611101737y3914be8aqfc91332f27dcc697@mail.gmail.com> hi, Can anyone tell me how to create a soap web service and generate it's WSDL file?? I've tried so har to do so but no results. cheers OnemoverX From Daniel.Trstenjak at science-computing.de Tue Nov 28 09:49:22 2006 From: Daniel.Trstenjak at science-computing.de (Daniel Trstenjak) Date: Tue, 28 Nov 2006 14:49:22 +0000 (UTC) Subject: 'locals' argument of PyEval_EvalCode Message-ID: <20061128144918.GB13212@bug.science-computing.de> Hi all, I would like to know the definition of the 'locals' object given to PyEval_EvalCode. Has 'locals' to be a python dictionary or a subtype of a python dictionary, or is it enough if the object implements the necessary protocols? The python implementation behaves different for the two following code lines: from modul import symbol from modul import * In the case of the first one, it's enough if the object 'locals' implements the necessary protocols. The second one only works if the object 'locals' is a type or subtype of dictionary. Best Regards, Daniel From george.sakkis at gmail.com Mon Nov 27 21:42:54 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 27 Nov 2006 18:42:54 -0800 Subject: Python script and C++ References: <456b83c7$1@clarion.carno.net.au> Message-ID: <1164681774.129138.210780@j44g2000cwa.googlegroups.com> Thuan Seah Tan wrote: > Hi all, > > I am new to python and currently I am working on a traffic simulation > which I plan to define the various agents using scripting. It's kind of like > scripting for non-playable character in games. I am thinking of using python > for this but I am concerned with running time. Is scripting a lot slower > compared to direct implementation in C++? Does compiling the script help in > any way? Also, can anyone recommend me a book that covers python in general > as well as C++ binding? Thanks. Even if pure python turns out to be slow for some critical parts of your application, there are quite a few ways to deal with it: psyco, pyrex, weave/blitz, ctypes, SWIG, Boost-python, SIP, CXX, SCXX, hand-written C extensions and perhaps more. Visit http://www.scipy.org/PerformancePython for an example of taking a simple pure Python function and boosting it using several different tools. Check out the final comparison table first; the pyrex version is less than half a second slower than the C++. George From tdelaney at avaya.com Tue Nov 14 23:40:16 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 15 Nov 2006 15:40:16 +1100 Subject: Python development time is faster. Message-ID: <2773CAC687FD5F4689F526998C7E4E5F07443D@au3010avexu1.global.avaya.com> ?ric Daigneault wrote: > This being said.... after a bit of experience in programming, design > patterns and other marvels of the modern brains, doing bad code in > python requires a conscious effort to do. The bright side is that it > gives all the justification to reviewers to smack the offenders on > the head with a hardcover copy of the GoF. Thankfully that book retains some usefulness as a LART, because about 90% of what's not printed on the inside front and rear covers is made redundant by using Python . Tim Delaney From python.list at tim.thechases.com Tue Nov 7 16:34:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 07 Nov 2006 15:34:09 -0600 Subject: sqlite query not working In-Reply-To: <4550f7a5$0$14445$c3e8da3@news.astraweb.com> References: <4550f36e$0$8780$c3e8da3@news.astraweb.com> <4550f7a5$0$14445$c3e8da3@news.astraweb.com> Message-ID: <4550FBD1.6080703@tim.thechases.com> >> Have you tried adding a self.connection.commit() to the >> code? I don't know whether sqlite is transactional, but if >> it is then the changes will disappear without a commit. > > Wow, that worked! Now, I know I've done some DB work before > (very similar to this) and never used commit(), so I'm > confused but still grateful! :) I tinkered with the mx.ODBC drivers a bit and had a similar difficulty until I realized that it was configured to *not* autocommit. At least in the mx.ODBC drivers, you can pass a param ("clear_auto_commit=1") to the Connect() call to restore "normal" autocommiting behavior. I can see both sides of the fence...it's just a hassle to sniff out which DB drivers autocommit and which don't. -tkc From horpner at yahoo.com Fri Nov 10 09:23:43 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Nov 2006 15:23:43 +0100 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> Message-ID: On 2006-11-09, Bjoern Schliessmann wrote: > What about > > if color == red or blue or green: > return 'primary' > >:) The Inform 6* programming language supports the serial 'or' (and 'and') and looks just like that. The disadvantage is that the usual binary logical operators must exist and are spelled differently. (It uses C's '||' and '&&'.) if (color == red or blue or green && color.type == additive) { return 'primary'; } It also supports a switch statement syntax and semantics that would fit nicely with Python. switch (action) { Eat: print "Gulp! Delicious, but poisonous."; deadflag = 1; Taste: print "You nibble at one of the corners. Yum!"; Attack: print "What did that mushroom ever to to you?"; default: print "You can't do that to a mushroom."; } There's no fall-through, and there's no syntax to enable it, either. In Python it would hypothetically be: switch action: Eat: print "Gulp! Delicious, but poisonous." deadflag = True Taste: print "You nibble at one of the corners. Yum!" Attack: print "What did the mushroom ever to to you?" default: print "You can't do that to a mushroom." I've often wanted a "Pythonic" Inform to Inform translator, so I can leave out all the unecessary (), {} and ;. * Inform 6 is a language for implementing text adventures, not to be confused with the unrelated language Inform 7. -- Neil Cerutti From http Fri Nov 3 19:16:52 2006 From: http (Paul Rubin) Date: 03 Nov 2006 16:16:52 -0800 Subject: Javascript is turning into Python?! References: <7xslh1dmgt.fsf_-_@ruckus.brouhaha.com> <1162596267.518634.164170@h54g2000cwb.googlegroups.com> Message-ID: <7xr6wkt6a3.fsf@ruckus.brouhaha.com> "Carl Banks" writes: > > http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7 > Maybe in exchange, Python can borrow the let statement. Maybe the with statement could be extended to allow binding more than one variable. with x as f(), y as g(): blah (x, y) From fredrik at pythonware.com Mon Nov 20 05:13:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Nov 2006 11:13:04 +0100 Subject: trying to create a dictionary in python, using variables as a value In-Reply-To: <1164016765.497299.193830@b28g2000cwb.googlegroups.com> References: <1164008459.159792.48600@k70g2000cwa.googlegroups.com> <1164016765.497299.193830@b28g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > On this one what? It would help very much if you showed the one > statement that is getting the syntax error. on which statement does he *not* get a syntax error? From tim at tdw.net Wed Nov 8 19:24:35 2006 From: tim at tdw.net (Tim Williams) Date: Thu, 9 Nov 2006 00:24:35 +0000 Subject: Python to tell what is the IP of my PC . In-Reply-To: References: <9afea2ac0611081600r7b2deb49pde0a6477bab7c7ca@mail.gmail.com> Message-ID: <9afea2ac0611081624s8df6b07k946a088b1067124f@mail.gmail.com> On 09/11/06, Nicolas G wrote: > > > On 11/9/06, Tim Williams wrote: > > On 8 Nov 2006 15:35:31 -0800, NicolasG wrote: > > > How can I use python to get the real IP address of my DSL router (when > > > my PC is part of the local home LAN) ? > > > > The router will the PC's default gateway IP address, if you are on a > > windows platform, you can view it by typing IPCONFIG (enter) from a > > command prompt. > > This is the router local IP, I need to get the router "outside" IP witch is > the real one. Oh sorry I missed that. In that case, get a free dynamic hostname from someone like noip.com. Install their client on your PC. The client will keep the hostname updated with your "real" external IP address, and you can use socket.gethostbyname(hostname) to query it. It will only take a few minutes to set up the NO-IP account and client :) From tim at tdw.net Fri Nov 10 11:25:58 2006 From: tim at tdw.net (Tim Williams) Date: Fri, 10 Nov 2006 16:25:58 +0000 Subject: Getting externally-facing IP address? In-Reply-To: <9afea2ac0611100825o1115c188uc89ee1fbe0434717@mail.gmail.com> References: <9afea2ac0611100825o1115c188uc89ee1fbe0434717@mail.gmail.com> Message-ID: <9afea2ac0611100825x373fe801idc671e7f74e3ee2f@mail.gmail.com> On 10/11/06, Tim Williams wrote: > > > On 10/11/06, Michael B. Trausch wrote: > > > > > > > > Every programming example that I have seen thus far shows simple server > code and how to bind to a socket--however, every example binds to the > localhost address. What I am wondering is this: Is there a clean way to > get the networked IP address of the machine the code is running on? For > example, my laptop's IP address is 192.168.0.101, and I want to bind a > server to that address. Is there a clean way of doing so that will work, > for example, when I move the code to my server (which obviously doesn't have > the same IP address)? > > > > > > Try using 0.0.0.0 as the IP address, or possibly giving IP address at > all. > > HTH :) > > Correction: -> or possibly giving *no* IP address at From greenbergj at NOSPAMwit.edu Sun Nov 26 22:23:09 2006 From: greenbergj at NOSPAMwit.edu (Jordan Greenberg) Date: Sun, 26 Nov 2006 22:23:09 -0500 Subject: test message In-Reply-To: <9fckm2p839oh7c586t93c9fn3lfppu43g3@4ax.com> References: <9fckm2p839oh7c586t93c9fn3lfppu43g3@4ax.com> Message-ID: <456A5A1D.60309@NOSPAMwit.edu> john.smith at nowhere.com wrote: > This is a test message, please ignore. I could do that, but reminding you that test messages go in *.test groups is way more fun. And there are about a billion of them to choose from. The great thing about test groups is that when you use them, you don't clutter up my (and everyone else's) newsreader with your garbage. Thanks, Jordan -- Posted via a free Usenet account from http://www.teranews.com From theller at ctypes.org Sun Nov 19 11:11:50 2006 From: theller at ctypes.org (Thomas Heller) Date: Sun, 19 Nov 2006 17:11:50 +0100 Subject: how to print pdf with python on a inkjet printer. In-Reply-To: <7.0.1.0.0.20061117222832.040fd658@yahoo.com.ar> References: <455E1E59.4030501@probo.com> <7.0.1.0.0.20061117222832.040fd658@yahoo.com.ar> Message-ID: <45608246.7050207@ctypes.org> Gabriel Genellina schrieb: > At Friday 17/11/2006 17:40, Tim Roberts wrote: > >> > double wow! as it is my customer wants me to print to the default >> > printer. >> > can you please help me with the command for rendering the pdf to the >> > printer with acrobat using python? >> >>You'll have to use the registry to find "acrord32", but once you find >>it, you just do: >> os.system( "\\Program Files\\Adobe\\Acrobat 7.0\\Reader\acrord32.exe >>/p xxx.pdf" ) >>The /p switch requests printing. > > Or just let Windows do the dirty work of locating Adobe Reader, > figuring out the parameters and such: > > import win32api > win32api.ShellExecute(0, "print", path/to/document.pdf, None, None, 0) > Note that in Pyhton2.5, os.startfile was extended to accept an optional second parameter; so os.startfile(path/to/document.pdf, "print") should also work. Thomas From horpner at yahoo.com Fri Nov 10 08:20:15 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Nov 2006 14:20:15 +0100 Subject: how is python not the same as java? References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> Message-ID: On 2006-11-10, gavino wrote: > both are interpreted oo langauges...... "..." -- Neil Cerutti From alan.franzoni.xyz at gmail.com.invalid Sun Nov 19 09:13:30 2006 From: alan.franzoni.xyz at gmail.com.invalid (Alan Franzoni) Date: Sun, 19 Nov 2006 15:13:30 +0100 Subject: A python IDE for teaching that supports cyrillic i/o References: Message-ID: <1knc9a9960uon.slnj7e17d24m$.dlg@40tude.net> Kirill Simonov si ? divertito a scrivere: > On Sun, Nov 19, 2006 at 12:33:39PM +0100, Alan Franzoni wrote: > No, I would prefer the editor to save the .py files with non-ASCII > characters in UTF-8 encoding adding the BOM at the beginning of the > file. This will allow the interpreted to detect the file encoding > correctly and would save a teacher from explaining what an encoding is > and why it is needed. You'll run into encoding problems anyway in your programmer's life. I don't think it's a workaround, try this article: http://www.joelonsoftware.com/articles/Unicode.html I think it's highly useful, you could tell that to your students. BTW, not every editor supports the BOM. Have you tried with the explicit encoding line: # -*- coding: utf-8 -*- Eclipse+Pydev seems to work with that. I'm not able to check with other editors right now, but it seems you're experiencing a simple encoding problem; your editor doesn't know which encoding you'd like to use, so it defaults to ascii or iso-8859-1 leading to such problems. -- 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 Jack.Andrews at boeing.com Sun Nov 19 18:26:29 2006 From: Jack.Andrews at boeing.com (EXI-Andrews, Jack) Date: Mon, 20 Nov 2006 09:26:29 +1000 Subject: re.match -- not greedy? Message-ID: <750FA239330A7E4CA15D456F37DFF8AE02500B03@XCH-AU-01.au.nos.boeing.com> the '*' and '+' don't seem to be greedy.. they will consume less in order to match a string: >>> import re;re.match('(a+)(ab)','aaab').groups() ('aa', 'ab') this is the sort of behaviour i'd expect from '(a+?)(ab)' a+ should greedily consume a's at the expense of the string not matching in real life, i am trying to match #defines: >>> re.match( '#define ([A-Za-z0-9_]+)([^(])', '#define abc(d)').groups() ('ab', 'c') i want this example to fail because the first character after a string of letters is a '(' i want to match only #defines without parameters. so what's the definition of greedy? (pls copy me on responses) ta, jack From amitsoni.1984 at gmail.com Tue Nov 7 14:49:26 2006 From: amitsoni.1984 at gmail.com (amitsoni.1984 at gmail.com) Date: 7 Nov 2006 11:49:26 -0800 Subject: changing sequence to array Message-ID: <1162928966.444452.75220@h54g2000cwb.googlegroups.com> Hi, I am using the code given below where A is a matrix and row is a sequence. But it gives following error: -------- error------ A[a,:]=row ValueError: setting an array element with a sequence. --------------code---------------- #!/usr/bin/python import numpy file1 = open('matrix.txt', 'r') count = 0 a=0 b=0 c=0 d=0 e=0 A = numpy.zeros([4,4]) B= numpy.zeros([4,4]) C = numpy.zeros([4,4]) D = numpy.zeros([4,4]) E = numpy.zeros([4,4]) while 1: lineStr = file1.readline() if not(lineStr): break count = count + 1 row=lineStr.split() if count<=4: A[a,:]=row a=a+1 elif count<=8: B[b,:]=row b=b+1 elif count<=12: C[c,:]=row c=c+1 elif count<=16: D[d,:]=row d=d+1 elif count<=20: E[e,:]=row e=e+1 file1.close() ---------end of code------------- is there any way to change a sequence to array so that the above operation could be executed? thank you Amit From duncan.booth at invalid.invalid Thu Nov 30 05:42:03 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Nov 2006 10:42:03 GMT Subject: Slicing versus loops, was Re: for i in range() anti-pattern References: <1164812827.653386.323320@80g2000cwy.googlegroups.com> Message-ID: Peter Otten <__peter__ at web.de> wrote: > That example was chosen to prove your point. The real contender for the > "swap items" problem are slices. > > def swap_slice(items): > left = items[::2] > items[::2] = items[1::2] > items[1::2] = left > return items > It makes no difference to the time or memory use, but you can of course also write swap_slice using the aforementioned 'well known idiom': items[::2], items[1::2] = items[1::2], items[::2] From ptmcg at austin.rr._bogus_.com Mon Nov 27 10:28:54 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 27 Nov 2006 15:28:54 GMT Subject: Persistent Threads & Synchronisation References: Message-ID: "Matthew Tylee Atkinson" wrote in message news:ekbtqe$74s$2 at news.freedom2surf.net... >I appear to be having some problems with the isAlive() method of > detecting if a thread is alive/active/running or not. I'd be grateful > for any advice. > Your comments about restartable threads got me thinking about generators. While this does not strictly do threading, this little example uses a list of generators, which save their state and pick up where they left off. (Also, look into simpy, which has a similar concept, but much more infrastructure support). -- Paul class Processor(object): def __init__(self, id_): self.id = id_ self.finished = False def __str__(self): return "Processor: %s" % self.id def run(self): def runImpl_(self): runGen = self.runImpl() while not self.finished: try: yield self.id,runGen.next() except StopIteration: self.finished = True return runImpl_(self) def runImpl(self): times = 0 while times < self.id: times += 1 yield times import random class RandomProcessor(Processor): # just implement runImpl in subclass def runImpl(self): times = 0 while times < self.id: times += 1 yield random.random() def main(): # create list of processors procList =[ (random.choice([True,False]) and Processor(i) or RandomProcessor(i)) for i in range(10)] procs = [ (p,p.run()) for p in procList ] # context switch loop while procs: # cycle through all processors for p in procs: try: ret = p[1].next() print ret except StopIteration: pass # remove any processors that have finished procs = [ p for p in procs if not p[0].finished ] main() From steven.bethard at gmail.com Fri Nov 3 12:57:30 2006 From: steven.bethard at gmail.com (steven.bethard at gmail.com) Date: Fri, 3 Nov 2006 17:57:30 +0000 (GMT) Subject: python-dev Summary for 2006-09-16 through 2006-09-30 Message-ID: <20061103175732.7F93B1E4004@bag.python.org> python-dev Summary for 2006-09-16 through 2006-09-30 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-09-16_2006-09-30] ========= Summaries ========= --------------- Import features --------------- Fabio Zadrozny ran into the `previously reported relative import issues`_ where a ``from . import xxx`` always fails from a top-level module. This is because relative imports rely on the ``__name__`` of a module, so when it is just ``"__main__"``, they can't handle it properly. On the subject of imports, Guido said that one of the missing import features was to be able to say "*this* package lives *here*". Paul Moore whipped up a Python API to an import hook that could do this, but indicated that a full mechanism would need to pay more attention to the environment (e.g. PYTHONPATH and .pth files). There was also some discussion about trying to have a sort of per-module ``sys.path`` so that you could have multiple versions of the same module present, with different modules importing different versions. Phillip J. Eby suggested that this was probably not a very common need, and that implementing it would be quite difficult with things like C extensions only being able to be loaded once. In general, people seemed interested in a pure-Python implementation of the import mechanism so that they could play with some of these approaches. It looked like Brett Cannon would probably be working on that. .. _previously reported relative import issues: http://www.python.org/dev/summary/2006-06-16_2006-06-30/#relative-imports-and-pep-338-executing-modules-as-scripts Contributing thread: - `New relative import issue `__ ---------------------------- Python library documentation ---------------------------- A less-trolly-than-usual post from Xah Lee started a discussion about the Python documentation. Greg Ewing and others suggested following the documentation style of the Inside Macintosh series: first an "About this module" narrative explaining the concepts and how they fit together, followed by the extensive API reference. Most people agreed that simply extracting the documentation from the docstrings was a bad idea -- it lacks the high-level overview and gives equal importance to all functions, regardless of their use. Contributing thread: - `Python Doc problems `__ ----------------------- OS X universal binaries ----------------------- Jack Howarth asked about creating universal binaries for OS X that would support 32-bit or 64-bit on both PPC and x86. Ronald Oussoren pointed out that the 32-bit part of this was already supported, but indicated that adding 64-bit support simultaneously might be more difficult. Ronald and Martin v. Lowis discussed strategies for modifying pyconfig.h, though it seemed these solutions might cause distutils to detect some architecture features incorrectly. Martin suggested that this was more a problem of distutils than pyconfig.h. Contributing thread: - `python, lipo and the future? `__ ---------------------------------- Finer-grained locking than the GIL ---------------------------------- Martin Devera was looking into replacing the global interpreter lock (GIL) with finer-grained locking, tuned to minimize locking by assuming that most objects were used only by a single thread. For objects that were shared across multiple threads, this approach would allow non-blocking reads, but require all threads to "come home" before modifications could be made. Phillip J. Eby pointed out that most object accesses in Python are actually modifications too, due to reference counting, so it looked like Martin's proposal wouldn't work well with the current refcounting implementation of Python. After Martin v. Lowis found a bug in the locking algorithm, Martin Devera decided to take his idea back to the drawing board. Contributing thread: - `deja-vu .. python locking `__ --------------------------- OS X and ssize_t formatting --------------------------- The buildbots spotted an OS X error in the itertools module. After Jack Diederich fixed a bug where ``size_t`` had been used instead of ``ssize_t``, Neal Norwitz noticed some problems with ``%zd`` on OS X. Despite documentation to the contrary in both the man page and the C99 Standard, using that specifier on OS X treats a negative number as an unsigned number. Ronald Oussoren and others reported the bug to Apple. Contributing thread: - `test_itertools fails for trunk on x86 OS X machine `__ ------------------- itertools.flatten() ------------------- Michael Foord asked about including a flatten function that would take a sequence with sub-sequences nested to an arbitrary depth and create a simple non-nested sequence from that. People were strongly opposed to adding this as a builtin, but even as an itertools function, there was disagreement. How should strings, dicts and other arbitrary iterables be flattened? Since there wasn't one clear answer, it looked like the proposal didn't have much of a chance. Contributing thread: - `Suggestion for a new built-in - flatten `__ ------------------------------- Class definition syntax changes ------------------------------- Fabio Zadrozny noted that in Python 2.5, classes can now be declared as:: class C(): ... Some folks wanted the result to be a new-style class, but the presence or absence of ``()`` was deemed too subtle of a cue to make the new-style/old-style distinction. For the Python 2.X series, explicit subclassing of ``object`` will still be necessary. Contributing thread: - `Grammar change in classdef `__ ---------------------- Python 2.5 and GCC 4.2 ---------------------- Armin Rigo found some more signed integer overflows when using GCC 4.2 like the ones `reported earlier`_. Because Python 2.5 final was scheduled to be released in 24 hours, and it looked like there wouldn't be too many people affected these problems, they were deferred until 2.5.1. For the moment at least, the README indicates that GCC 4.1 and 4.2 shouldn't be used to compile Python. .. _reported earlier: http://www.python.org/dev/summary/2006-08-16_2006-08-31/#gcc-4-2-and-integer-overflows Contributing threads: - `Before 2.5 - More signed integer overflows `__ - `GCC 4.x incompatibility `__ ---------------------------------- Discard method for dicts and lists ---------------------------------- Gustavo Niemeyer and Greg Ewing suggested adding ``dict.discard()`` and ``list.discard()`` along the lines of ``set.discard()``. Fred L. Drake, Jr. explained that ``dict.discard(foo)`` is currently supported with ``dict.pop(foo, None)``. There was more debate about the ``list`` version, but most people seemed to think that wrapping ``list.remove()`` with the appropriate if-statement or try-except was fine. Contributing threads: - `dict.discard `__ - `list.discard? (Re: dict.discard) `__ -------------------- weakref enhancements -------------------- tomer filiba offered some additions to the weakref module, weakattr_ and weakmethod_. Raymond Hettinger questioned how frequently these would be useful in the real world, but both tomer and Alex Martelli assured him that they had real-world use-cases for these. However, there didn't generally seem to be enough support for them to include them in the standard library. .. _weakattr: http://sebulba.wikispaces.com/recipe+weakattr .. _weakmethod: http://sebulba.wikispaces.com/recipe+weakmethod Contributing thread: - `weakref enhancements `__ ------------------------ AST structure guarantees ------------------------ Anthony Baxter asked that the AST structure get the same guarantees as the byte-code format, that is, that it would change as little as possible so that people who wanted to hack it wouldn't have to change their code for each release. Pretty much everyone agreed that this was a good idea. In a related thread, Sanghyeon Seo asked if the AST structure should become part of the Python specification so that other implementations like IronPython_ would use it as well. While most people felt like it would be good if the various specifications had similar AST representations, it seemed like mandating it as part of the implementation would lock things down too much. .. _IronPython: http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython Contributing threads: - `IronPython and AST branch `__ - `IronPython and AST branch `__ - `AST structure and maintenance branches `__ ----------------------------- PEP 302: phase 2 import hooks ----------------------------- For his dissertation work, Brett Cannon needed to implement phase 2 of the `PEP 302`_ import hooks. He asked for feedback on whether it would be easier to do this within the current C code, or whether it would be better to rewrite the import mechanisms in Python first. Phillip J. Eby gave some advice on how to restructure things, and suggested that the C code was somewhat delicate and having a Python implementation around would be a Good Thing. Armin Rigo strongly recommended rewriting things in Python. .. _PEP 302: http://www.python.org/dev/peps/pep-0302/ Contributing thread: - `difficulty of implementing phase 2 of PEP 302 in Python source `__ -------------------------------------- Testsuite, Windows and spaces in paths -------------------------------------- Martin v. Lowis was trying to fix some bugs where spaces in Windows paths caused some of the testsuite to fail. For example, test_popen was getting an error because ``os.popen`` invoked:: cmd.exe /c "c:\Program Files\python25\python.exe" -c "import sys;print sys.version" which failed complaining that c:\Program is not a valid executable. Jean-Paul Calderon and Tim Peters explained that the ``cmd.exe`` part is necessary to force proper cmd.exe-style argument parsing and to allow environment variable substitution. After scrutinizing the MS quoting rules, it seemed like fixing this for Python 2.5 was too likely to introduce incompatibilities, so it was postponed to 2.6. Contributing thread: - `Testsuite fails on Windows if a space is in the path `__ ----------------------------------------- PEP 353: Backwards-compatibility #defines ----------------------------------------- David Abrahams suggested a modification to the suggested backwards-compatibility #define incantation of `PEP 353`_ so that the PY_SSIZE_T_MAX and PY_SSIZE_T_MIN would only ever get defined once. There was some discussion about whether or not this was absolutely necessary, but everyone agreed that the change was probably sensible regardless. .. _PEP 353: http://www.python.org/dev/peps/pep-0353/ Contributing thread: - `Pep 353: Py_ssize_t advice `__ ---------------- Shrinking Python ---------------- Milan Krcmar asked about what he could drop from Python to make it small enough to fit on a platform with only 2 MiB of flash ROM and 16 MiB of RAM. Giovanni Bajo suggested dropping the CJK codecs (which account for about 800K), though he also noted that after that there weren't any really low-hanging fruit. Martin v. Lowis suggested that he might also get a gain out of dropping support for dynamic loading of extension modules, and linking all necessary modules statically. Gustavo Niemeyer pointed him to `Python for S60`_ and `Python for Maemo`_ which had to undergo similar stripping down. .. _Python for S60: http://opensource.nokia.com/projects/pythonfors60/ .. _Python for Maemo: http://pymaemo.sf.net Contributing thread: - `Minipython `__ ================ Deferred Threads ================ - `Removing __del__ `__ - `Caching float(0.0) `__ - `PEP 355 status `__ - `PEP 351 - do while `__ ================== Previous Summaries ================== - `Signals, threads, blocking C functions `__ =============== Skipped Threads =============== - `Thank you all `__ - `BRANCH FREEZE/IMMINENT RELEASE: Python 2.5 (final). 2006-09-19, 00:00UTC `__ - `RELEASED Python 2.5 (FINAL) `__ - `release25-maint branch - please keep frozen for a day or two more. `__ - `Download URL typo `__ - `Exceptions and slicing `__ - `Weekly Python Patch/Bug Summary `__ - `release25-maint is UNFROZEN `__ - `Small Py3k task: fix modulefinder.py `__ - `win32 - results from Lib/test - 2.5 release-maint `__ - `Weekly Python Patch/Bug Summary ** REVISED ** `__ - `[Python-checkins] release25-maint is UNFROZEN `__ - `Python network Programmign `__ - `Relative import bug? `__ - `GCC patch for catching errors in PyArg_ParseTuple `__ - `Typo.pl scan of Python 2.5 source code `__ - `Maybe we should have a C++ extension for testing... `__ - `Python 2.5 bug? Changes in behavior of traceback module `__ - `Need help with C - problem in sqlite3 module `__ - `PyErr_CheckSignals error return value `__ - `python-dev summary for 2006-08-01 to 2006-08-15 `__ - `2.4.4c1 October 11, 2.4.4 final October 18 `__ - `[SECUNIA] "buffer overrun in repr() for unicode strings" Potential Vulnerability (fwd) `__ - `List of candidate 2.4.4 bugs? `__ - `openssl - was: 2.4.4c1 October 11, 2.4.4 final October 18 `__ - `Collecting 2.4.4 fixes `__ - `os.unlink() closes file? `__ - `Tix not included in 2.5 for Windows `__ - `Possible semantic changes for PEP 352 in 2.6 `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from September 16, 2006 through September 30, 2006. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This python-dev summary is the 13th written by Steve Bethard. To contact me, please send email: - Steve Bethard (steven.bethard at gmail.com) Do *not* post to comp.lang.python if you wish to reach me. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every cent counts so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- This summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo :); you can safely ignore it. We do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. .. _python-dev: http://www.python.org/dev/ .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _Python Software Foundation: http://python.org/psf/ .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From jscrerar at compuserve.com Fri Nov 24 13:26:26 2006 From: jscrerar at compuserve.com (Jim) Date: 24 Nov 2006 10:26:26 -0800 Subject: How do I access a main frunction from an import module? In-Reply-To: <1164390207.777502.24220@h54g2000cwb.googlegroups.com> References: <1164377547.562483.152770@l12g2000cwl.googlegroups.com> <1164390207.777502.24220@h54g2000cwb.googlegroups.com> Message-ID: <1164392786.339330.161940@h54g2000cwb.googlegroups.com> John Machin wrote: > Jim wrote: > > Hi, > > > > I have created an import module. And would like to access a function > > from the main script, e.g., > > > > file abc.py: > > ################### > > def a(): > > m() > > return None > > #################### > > > > file main.py: > > ##################### > > from abc import * > > def m(): > > print 'something' > > return None > > > > a() > > ###################### > > > > python25.exe main.py > > > > Although there are literally correct answers to your question, the best > answer is "Don't do that. You would be creating circular references > between modules, and run the risk of emulating the mythical ooloo bird > by disappearing up your own fundamental orifice". Some possible > practical solutions: > > 1. Put the m function in a 3rd file/module. Then any other module which > needs it can import/call. > > 2. If you think that's not a good idea, then put it in abc.py (it's not > used in main.py in your example). > > 3. Maybe this will suit what you are really trying to do: > > file abc.py: > ################### > def a(argfunc): # <<<<<===== > argfunc() # <<<<<===== > #################### > > file main.py: > ##################### > from abc import * > def m(): > print 'something' > > a(m) # <<<<<===== > ###################### > > 4. If you think *that's* not a good idea, then you might like to > explain at a higher level what you are *really* trying to achieve :-) > E.g. "Function m is one of n functions in main.py of which abc.py > may/must call 0, 1, or many because blah blah blah ..." > > BTW, "return None" at the very end of a function is redundant. The > Python compiler generates "return None" automagically (implicitly!?) > instead of letting you fall off the end of the world. Which book or > tutorial are you using? > > BTW #2: "python25.exe main.py" ?? If you are on Windows, have Python > 2.4 as your default setup, and are trialling 2.5: you may like to ask > (in a new thread) about more convenient ways of doing it. Otherwise you > might like to tell what you are up to (in a new thread) so that your > problem can be diagnosed correctly and cured :-) > > HTH, > John BTW#1: I have most of the python books from O'Reilly. I'm sure that some of them say that its a good idea to use 'return None'. However, most their examples do not us it. Anyway I find that its useful when reading my own scripts. BTW#2: I do not have Python 2.4 installed anymore. Therefore, it is not a trialling problem. I thought that it would be NICE to keep the application and the user's script separate from each other, being that python is so flexible. However, there seems to be no end to the problems that occur by doing this. So I will abandon this exercise, since it appears not to be a very good programming practise. Thanks, Jim From superflit at gmail.com Mon Nov 13 12:13:29 2006 From: superflit at gmail.com (flit) Date: 13 Nov 2006 09:13:29 -0800 Subject: Python development time is faster. In-Reply-To: <1163425734.640509.99420@m73g2000cwd.googlegroups.com> References: <1163425734.640509.99420@m73g2000cwd.googlegroups.com> Message-ID: <1163438009.505835.326970@m73g2000cwd.googlegroups.com> One thing I really like, is making "prototypes" on python. Just to test some algorithm or procedure. It is very fast and easy to debug. So after, I make it in c++ (but not too much often, I leave it in python today.) Chris Brat wrote: > I've seen a few posts, columns and articles which state that one of the > advantages of Python is that code can be developed x times faster than > languages such as <>. > > Does anyone have any comments on that statement from personal > experience? > How is this comparison measured? > > > Thanks > Chris From tleeuwenburg at gmail.com Mon Nov 20 22:44:30 2006 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 20 Nov 2006 19:44:30 -0800 Subject: The Python Papers Edition One Message-ID: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> Greetings all, Some of you may have noticed the launch of the Python Journal a while back. Due to artistic differences, the journal has now been re-launched as The Python Papers. It is available under a Creative Commons License, something we felt was appropriate given its nature. Many here commented that this was important to them, and it is important to us also. For a fuller description of what we hope the journal to be, I re-create my inaugural blog posting at the end of this email, or it can be found online here: http://pythonpapers.cgpublisher.com/diary Some of you had a number of specific points to raise, which I can now answer properly since launching under our own banner. 1.) It takes too many clicks to download. A) We know, but it's like that to save our server. We will be publishing to a number of online archives, back-issues may be back-linkable from those. 2.) Is it free? A) Yes, as in beer and as in freedom. Creative Commons 2.5 Noncommercial, attribution, share-alike. 3.) Can I have an HTML version? A) No, we like it pretty. 4.) Why not try (insert favourite thing here) A) We will. Thanks for the fish. " Volume 1, Edition 1 makes history Welcome to The Python Papers. This journal, small though it is, represents the careful efforts of a small group of Python enthusiasts who are keen to form a better community in which developers may work. As Editor-In-Chief, my role is manifold, but my goals are to improve the level of connectedness of Python developers, and in so doing improve my own developer experience. The entire editorial board has put time into making this publication something which will hopefully lead to a buildup of momentum, fuelled by the enthusiastic involvement of others who find Python as exciting as we do. The current issue contains one academic, peer-reviewed article, one industry article, and a list of events coming up in Melbourne, Australia. We would like to expand this list significantly. We offer our services in organising, collating and reviewing submitted content such that Python developers around the world may participate in the creation of something bigger than all of us, for the benefit of all of us. It may be a small journal, a little thing really, but all are welcome, and we look forward to getting to know our readers through the written word. Please download the first edition, and consider both what it is and what it might be. For those of you looking to publish an academic paper as a part of coursework or for interest's sake alone, we can offer a formal review process which will meet those guidelines while preserving the goals of freedom of information and community spirit. Those who are using Python in their work may like to consider using the journal as a means of expressing successes or frustrations with either the language itself or specific applications. We may be able to offer code reviews and style guides, and would be happy to hear about and help propagate news of what is happening so that everyone can take an interest. For those who would like a reliable source of information, The Python Papers presents a unique and current view into the state of Python at large. To all of you, welcome! Cheers, -Tennessee (Editor-In-Chief)" From fredrik at pythonware.com Thu Nov 2 01:50:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 02 Nov 2006 07:50:04 +0100 Subject: Python images processing -recap In-Reply-To: References: Message-ID: alf wrote: > Are all supported, which is most mature, in which I could perform for > instance 'Ken Burns effect' that's a display effect, not an image effect. you need a display (or animation) library for that. From evenprimes at gmail.com Mon Nov 20 12:15:53 2006 From: evenprimes at gmail.com (Chris Cioffi) Date: Mon, 20 Nov 2006 12:15:53 -0500 Subject: OODB vs RDBMS In-Reply-To: <4se3omFv6reaU1@mid.individual.net> References: <4se3omFv6reaU1@mid.individual.net> Message-ID: You might want to look at either SQLObject or SQLAlchemy. They seem to handle the related join issues very nicely without resorting to calling SQL directly in your code. My only experience so far is using SQLObject with TurboGears and while it doesn't solve the issue of lots of tables, it makes the access code feel far more Pythonic than direct access. I use pyODBC for accessing corporate DB2 tables, and while having SQL in my code kinda sucks, it's fairly easy to write parametrized queries. If you create a DB access class you can encapsulate all your DB specific code and SQL in 1 place and then have access to things by method. Handy, but far from perfect. The Unicode issue is really related to your backend RDBMS, Python seems to handle whatever you throw at it. Still, be careful about how you construct your SQL so you don't open yourself to a SQL-injection like attack/bug. (I had a problem before I started using parametrized queries where the text I was INSERTing had a quote in it...:-/) Personally I would tend to be wary of DB specific extensions like the Postgres array. While you're using a modern Postgres today, what happens if you need to deploy on a slightly older version or on a different DBMS that doesn't support arrays? Creating foreign keys is simple and well supported by most of the majors. (I don't recall if MySQL has true fk support in v5 or not...) Chris On 20 Nov 2006 16:34:30 GMT, Thomas Guettler wrote: > Hi, > > most of the time I use ZODB/Durus to store my data. > > I like it, but I know that it has some weaknesses: > - only accesible from python > - I need to code your indexes for fast searching yourself. > > I think about using a RDBMS for the next project. What I don't like > about RDBMS: If you need a list of values you need to create a new > table. Example: If you want to store several email addresses of one > customer, you need to create a new table. > > Since the namespace if tablenames is flat, you soon have so many > tables, that it is hard to browse them. > > Postgres has extensions which allows you to store arrays in a column. Is > this supported by the python binding? Are there other databases which > support this? > > Are there OR-mappers (object relational mappers) which support lists in > a column? > > How is the unicode support of the python bindings to RDBMSs? I don't > want to convert the results of a query to unicode myself. > Can you insert unicode strings into a SELECT statement? > > Which database supports fulltext searches with a customized word > normalization? (All should be the same: str. str stra?e, strasse) > > Which OR-mapper do you suggest? > Are there OR-mappers which support this: Subobjects are > fetched automatically while you access the object tree? > Example: One customer has N TroubleTicketItems: > customerobj=get_customer(...) # First SELECT > for ticket in customerobj.tickets: # (*) > ... > > (*) Second SELECT gets executed only if needed. > > I now this message is vague, but maybe we can discuss the > pros/cons of "OODB vs RDBMS" > > Thomas > > > -- > Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ > E-Mail: guettli (*) thomas-guettler + de > Spam Catcher: niemand.leermann at thomas-guettler.de > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke From mail at microcorp.co.za Fri Nov 17 03:06:38 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 17 Nov 2006 10:06:38 +0200 Subject: Secure Python References: <455c1665@quokka.wn.com.au><455c4d9b@quokka.wn.com.au> Message-ID: <035601c70a1f$4f077060$03000080@hendrik> "Stephan Kuhagen" wrote: > The problem with linux kernel limits are, that they won't work really good > on MacOSX and Windows... OTOH the idea is the right one, but the effect can > be achieved inside of Python. Since Python does byte compile the code and > the interpreter evaluates each byte code token in one evaluation step. The > interpreter could be extended for such usecases to count and limit the > number of evaluation steps allowed for untrusted script or methods in > untrusted script as well as to limit the recursion depth or memory to be > allocated. All those limits are managed by the interpreter for script code > and hence can be limited for untrusted code by the interpreter. This also > does not really make DoS impossible (what about C extensions? - maybe > restricting "import"?). - As I said before in this thread, making a sandbox > really secure is a hard job, and may need some serious changes in the > Python interpreter, but AFAIK from Tcl, it is possible - and would be nice > to have. I seem to recall previous discussion on this group about a thing called the bastion module, and that it was deprecated. Not sure if it has any relevance. - Hendrik From Leo.Kislov at gmail.com Mon Nov 6 08:35:53 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 6 Nov 2006 05:35:53 -0800 Subject: Erronous "unsupported locale setting" ? References: Message-ID: <1162820153.697175.18190@h54g2000cwb.googlegroups.com> robert wrote: > Why can the default locale not be set by its true name? but only by '' ? : Probably it is just not implemented. But since locale names are system specific (For example windows accepts 'ch' as Chinese in Taiwan, where as IANA considers it Chamorro) setlocale should probably grow an additional keyword parameter: setlocale(LC_ALL, iana='de-DE') -- Leo From ronrsr at gmail.com Sun Nov 19 21:55:20 2006 From: ronrsr at gmail.com (ronrsr) Date: 19 Nov 2006 18:55:20 -0800 Subject: Not enough arguments for format string Message-ID: <1163991320.262638.154950@j44g2000cwa.googlegroups.com> is the error message I'm getting here, on the long formatted print statement. . I've tried adding arguments, in case I missed one, and it still gets a syntax error. here's the info: #row is a dictionary with keys: zid, keywords, citation, quotation def print_row(row): print row; print "row in print_row","kw=",row["keywords"],"q=",row["quotation"],"c = ",row["citation"],"xyzzy row" print """ %s %s %s """%row['keywords'],row['quotation'],row['citation'],row['zid'] print "done printrow xyzzy" here's the output, with my debugging info: {'keywords': 'Agricultural Subsidies, Farmers', 'zid': 319L, 'citation': '\xe2\x80\x9cAgriculture in Crisis,\xe2\x80\x9d Rethinking US Agricultural Policy: Changing Course to Secure Farmer Livelihoods Worldwide, September 2003, 9', 'quotation': 'In 2001, government payments to farmers amounted to an astounding 47 percent of farmer income, up from about 20 percent in the 1990s. Despite this enormous infusion of cash, farmer income declined steadily during the same period, and many US farmers are under increasing financial stress.'} row in print_row kw= Agricultural Subsidies, Farmers q= In 2001, government payments to farmers amounted to an astounding 47 percent of farmer income, up from about 20 percent in the 1990s. Despite this enormous infusion of cash, farmer income declined steadily during the same period, and many US farmers are under increasing financial stress. c = "Agriculture in Crisis," Rethinking US Agricultural Policy: Changing Course to Secure Farmer Livelihoods Worldwide, September 2003, 9 xyzzy row Traceback (most recent call last): File "C:\Documents and Settings\Ronald\My Documents\spi\zingers\public_html\display.py", line 116, in ? zhtml.print_row(adict) File "C:\Documents and Settings\Ronald\My Documents\spi\zingers\public_html\zhtml.py", line 222, in print_row print """ TypeError: not enough arguments for format string thanks once again, -rsr- From rvernica at gmail.com Fri Nov 3 21:38:33 2006 From: rvernica at gmail.com (Rares Vernica) Date: Fri, 03 Nov 2006 18:38:33 -0800 Subject: Physical constants In-Reply-To: <73D46C5F-12AE-4700-86D2-7FAE0DEF6C54@mac.com> References: <73D46C5F-12AE-4700-86D2-7FAE0DEF6C54@mac.com> Message-ID: Hi, I am not sure how the constants are implemented in math, but here is how I would do it. The main idea is to declare the constants as globals in some file. Declare all the constants in a file: const.py --- pi = 3.14 Whenever you want to use pi from another file, just do: somecode.py --- from const import pi a = 2 * pi Regards, Ray Tommy Grav wrote: > I have some code for doing orbital computations. The code is kind of > extensive with many classes, each having several functions. In these > functions I need to use constants (like the gravitational constant). > What is the best way of implementing a solution when constants are > used in several different classes and functions? I do not want to > pass the constant down through the functions. I have thought of > making a class of constants but I do not want to invoke an > instant in each function. How is the pi and e constants in math > coded? > > Tommy > > tgrav at mac.com > > http://homepage.mac.com/tgrav/ > > > "Any intelligent fool can make things bigger, > more complex, and more violent. It takes a > touch of genious -- and a lot of courage -- > to move in the opposite direction" > -- Albert Einstein > > From Google at Bodoin.com Mon Nov 13 13:05:12 2006 From: Google at Bodoin.com (Max) Date: 13 Nov 2006 10:05:12 -0800 Subject: httplib.ResponseNotReady question Message-ID: <1163441112.359818.208520@m7g2000cwm.googlegroups.com> Hi, Group. I'm not a Python programmer so this question may be really basic or stupid. :) I have some code that sends a simple request to an end-point and reads the response. That works just fine. When I put the code in a for loop though I get httplib.ResponseNotReady error message. It seems to me that I cannot call the requestor.getreply() multiple times on the same requestor object. Anyway, here's the part of my code that is causing the problem (I hope the format is preserved...). def sendRequest( msg, loops ): requestor = httplib.HTTP(SERVER_ADDR, SERVER_PORT) requestor.putrequest("POST", "/path/to/endpoint") requestor.putheader("Host", SERVER_ADDR) requestor.putheader("Content-Type", "text/xml") requestor.putheader("Content-Length", str(len( msg ) ) ) requestor.endheaders() for i in range(loops): requestor.send( msg ) print "[" + str(i) + "] Message Sent : " + time.strftime('%H:%M:%S', time.localtime()) (status_code, message, reply_headers) = requestor.getreply() print "[" + str(i) + "] Response Received : " + str(status_code) print "[" + str(i) + "] Status : " + time.strftime('%H:%M:%S', time.localtime()) print "-----[ break ]-----" If I run this with loops=1 then everything works fine. If I use a number greater than 1 then I get the error. Is there a method call that I need to restore the requestor object to a condition where it's eligible to receive another response? Thanks, Max From joel.hedlund at gmail.com Sat Nov 11 10:46:17 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Sat, 11 Nov 2006 16:46:17 +0100 Subject: import parser does not import parser.py in same dir on win In-Reply-To: References: Message-ID: > the table of built-in modules are checked before searching the path. I figured as much. But why is the behavior different on linux/win? Is this documented somewhere? /Joel From john106henry at hotmail.com Mon Nov 6 19:42:55 2006 From: john106henry at hotmail.com (John Henry) Date: 6 Nov 2006 16:42:55 -0800 Subject: wing ide vs. komodo? In-Reply-To: <1162708898.962171.161120@e3g2000cwe.googlegroups.com> References: <2nRXg.108$1n3.2866@news.tufts.edu> <1162690929.501897.258360@b28g2000cwb.googlegroups.com> <1162708898.962171.161120@e3g2000cwe.googlegroups.com> Message-ID: <1162860175.685031.90220@k70g2000cwa.googlegroups.com> "cool" is in the eyes of the beholder. While I agree that this can be useful in some situations, I find it very annoying when all I want (and need) to do is a simple dumber search and yet it tells me tons of useless searches that I don't care for. The inability to debug multi-threaded applications is pretty annoying too. It's unacceptable that a "professional" level debugger can't handle multithreaded code. But then again, I depend on Wing everyday. I just have to build my code with lots of "if debugging, don't thread else thread" type of constructs... vj wrote: > Forgot to mention WING's file search and replace is pretty cool and > powerful. It keeps checking changes in a different thread. If you want > to change yyy in say 100 files you would: > > 1. specify yyy in the search window > 2. A list of files get displayed with matching yyy > 3. As you fix replace yyy in the files the list of files with matching > yyy reduces automatically. This is very cool and very useful. > > Another thing I like about WING is that it warns you if you have tabs > ans spaces mixed in a file. > > The embedded python shell is also a useful feature. > > VJ From cvanarsdall at mvista.com Wed Nov 8 14:13:02 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 08 Nov 2006 11:13:02 -0800 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: <1163011320.632781.53370@m7g2000cwm.googlegroups.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> <1163011320.632781.53370@m7g2000cwm.googlegroups.com> Message-ID: <45522C3E.3050705@mvista.com> Paddy wrote: > Aahz wrote: > >> In article <1162997345.277966.31860 at h48g2000cwc.googlegroups.com>, >> Beliavsky wrote: >> >>> If this is supposed to justify using bad language in a public forum, >>> it is poorly reasoned. Having heard "f***" does not mean they were not >>> annoyed. 100% of people have seen trash on the street, but that does >>> not justify littering. If a group of people don't mind profanity, there >>> is no harm in their swearing to each other. But Usenet is read by a >>> wide range of people, and needlessly offending some of them is wrong. >>> The OP used "f******" just for emphasis. English is a rich language, >>> and there are better ways of doing that. >>> >> Oh, gimme a f****** break. Do a simple Gooja search to find out how >> often people already use "f***" around here. I think you're the one who >> needs to justify your position. >> -- >> Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ >> >> > I too know your wrong Aahz. The written word is not the same as that > spoken. People should make an effort to put across their meaning in a > clear manner. If I were going to an interview I would be very careful > about swearing and most likely not do it. People complain about the > friendliness and tone of groups, and mention it when talking about > programming languages. > > Not everyone swears like Eddy Murphy in Beverley Hills Cop, and a lot > of those that do, would not do so when they want to impress, or > communicate with a stranger. > > The tone of comp.lang.python *is* an asset, I think, to Python that > swearing will diminish. > You are comparing interviews to usenet. I somehow see a disconnect. I don't think many people are going to go to a potential employer and say "hey fuck face, how the fuck are ya?" Yea, its not likely to happen, in most cases people might even dress up to an interview and use all of their professionalisms as to not appear as they would at home. However communicating with people (cause that's what this is, its just people talking to one another about Python and the health of this forum) should be done as people see fit. Although you mentioned impressing people etc, is it really important to impress people here by watching your P's and Q's? What impresses me here is someone's command of the language, I could really give a rats ass how they choose to disseminate their expertise. As its been mentioned before, its one thing for me or anyone else to get in someone's face and be like "listen you little fuck, use a while loop." But that was clearly not the context. Using an expletive as an adjective does not diminish the "friendless" of the group unless you are complete prude. Granted, there are tons of them, I think that the real issue is that people need to learn to ignore things they don't like and not be so *damn* sensitive. Meaning is clearly conveyed, people's sensitivity is their own issue and I think too many people have gotten way to used to the political correctness shoved down our throats by society. Again, that's just my take on it, but those of you who would be offended by my statements and use of colorful language to describe my love of technology should probably just adjust your spam filters to scan for my name or emails that use words you can't handle. Its kind of like not watching tv shows that bother as opposed to raising a stink and having them taken off the air. Hopefully now the count is more like 124. /rant -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From thunderfoot at gmail.com Mon Nov 6 16:44:38 2006 From: thunderfoot at gmail.com (thunderfoot at gmail.com) Date: 6 Nov 2006 13:44:38 -0800 Subject: sqlite error? References: <454fa4dc$0$6987$c3e8da3@news.astraweb.com> Message-ID: <1162849478.092439.297160@i42g2000cwa.googlegroups.com> John Salerno wrote: > Am I using the ? placeholder wrong in this example? > > > t = ('hi', 'bye') > > self.connection.execute("INSERT INTO Personal (firstName, lastName) > VALUES ?", t) > > > > Traceback (most recent call last): > File "C:\Python25\myscripts\labdb\dbapp.py", line 93, in OnSaveRecord > self.save_to_database(textfield_values) > File "C:\Python25\myscripts\labdb\dbapp.py", line 97, in save_to_database > self.connection.execute("INSERT INTO Personal (firstName, lastName) > VALUES ?", t) > sqlite3.OperationalError: near "?": syntax error I believe you're missing the parens around your VALUES to insert. Also, you need 1 placeholder per argument inserted, not just one for the entire argument list. Try: self.connection.execute("INSERT INTO Personal (firstName, lastName) VALUES (?, ?)", t) HTH From markasoper at hotmail.com Wed Nov 22 15:16:55 2006 From: markasoper at hotmail.com (Mark S.) Date: 22 Nov 2006 12:16:55 -0800 Subject: Accessing feed history in an RSS Reader Message-ID: <1164226615.555781.169150@m73g2000cwd.googlegroups.com> Anyone know how to access feed history (items not contained in the current .xml file), so that an RSS Reader could display historical postings? Google Reader is able to do this. I'm interested in implementing kind of feature in Python. I've done quite a bit of searching to no avail. Any ideas? From apardon at forel.vub.ac.be Tue Nov 14 06:50:33 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Nov 2006 11:50:33 GMT Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <45538b0d$0$26485$c3e8da3@news.astraweb.com> <4558b437$0$32430$c3e8da3@news.astraweb.com> Message-ID: On 2006-11-13, Steve Holden wrote: > John Salerno wrote: >> Fredrik Lundh wrote: >>> John Salerno wrote: >>> >>>>> Anyway, the FAQ answer seems to be a weak argument to me. >>>> I agree. I was expecting something more technical to justify the >>>> colon, not just that it looks better. >>> yeah, the whole idea of treating programming languages as an interface >>> between people and computers is really lame. no wonder nobody's using >>> Python for anything. >>> >>> >>> >> >> personally, i don't mind the colon and see no need to lose it, but if we >> are talking in the realm of aesthetics, it actually seems like it would >> be cleaner if it weren't there...sure, at first everyone who is used to >> it might feel like something is missing, or the line is "hanging" open, >> but overall the less characters, the better, right? isn't that why the >> braces are gone? > > No. The braces are gone because they don't assist a reader's > determination of block structure like indentation does. IMO this works both ways. > Otherwise why > would people write indenting pretty printers for C and the like? Try to follow an indentation marked structure when the structure crosses a page boundary and you can't view the whole structure at once. Sensible placed markers can greatly assist in getting a feel for a structure even if the structure is already properly indented. -- Antoon Pardon From trentm at activestate.com Wed Nov 29 11:51:13 2006 From: trentm at activestate.com (Trent Mick) Date: Wed, 29 Nov 2006 08:51:13 -0800 Subject: pyxpcom In-Reply-To: References: Message-ID: <456DBA81.3070108@activestate.com> hg wrote: > Trent Mick wrote: >>> My need is as follows: I have developed an activex component to access a >>> smart card on the client side / do some web site logon. >>> >>> Are xpcom / pyxpcom advanced/stable enough for such an implementation >>> under Linux / Windows ? >> You mean to provide the equivalent functionality for Firefox that your >> activex component does for IE? Yes, xpcom and pyxpcom are quite stable, >> however putting together a Firefox extension that gets PyXPCOM itself up >> and running in a client's Firefox install will be quite challenging. >> >> Trent >> > Exactly ... are you saying I need to distribute Firefox compiled > differently in order to achieve that ? No. But you'll have to get comfortable building your own Firefox and then building the PyXPCOM extension and then packaging the built PyXPCOM bits that a normal Firefox install does not have already into a Firefox extension. This would also mean packaging up parts of a Python build and possible needing to have a custom Python build to (1) get shared library loading to work correct and (2) ensure there isn't crosstalk between the python that PyXPCOM uses and possibly other Python installations on the target machine. > This is less a python issue clearly if that is the case: would I have > the same issues to resolve if I were to write the module in C++ ? A little, yes: I believe you'd need a Firefox build in a development tree to build a vanilla C++ XPCOM component. However, I am not sure of that. Mostly, no: You wouldn't need to worry about all the PyXPCOM/Python build/install issues. Trent -- Trent Mick trentm at activestate.com From pipehappy at gmail.com Sun Nov 5 13:11:02 2006 From: pipehappy at gmail.com (pipehappy) Date: 5 Nov 2006 10:11:02 -0800 Subject: maybe this is a print odds Message-ID: <1162750262.316632.298600@e3g2000cwe.googlegroups.com> I come this code: 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. >>> class He(object): ... def __str__(self): ... return "He" ... >>> hes = [He(),He(),He()] >>> print hes [<__main__.He object at 0x00BE92D0>, <__main__.He object at 0x00BE9370>, <__main __.He object at 0x00BE93B0>] # I expect output: [He,He,He] >>> print hes[0] He >>> Do anyone know trick to overcome this or python has some proposal to extend print that can do iterately print? I just want to get the way of print which I my guess. Thanks a lot! From claird at lairds.us Mon Nov 6 19:52:51 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 7 Nov 2006 00:52:51 +0000 Subject: Unicode/ascii encoding nightmare References: <1162842650.780517.180360@b28g2000cwb.googlegroups.com> <1162846153.137536.116970@b28g2000cwb.googlegroups.com> <1162853677.881233.76940@m7g2000cwm.googlegroups.com> <1162854065.932910.99240@k70g2000cwa.googlegroups.com> Message-ID: <302524-2rs.ln1@lairds.us> In article <1162854065.932910.99240 at k70g2000cwa.googlegroups.com>, John Machin wrote: > >Thomas W wrote: >> Ok, I've cleaned up my code abit and it seems as if I've >> encoded/decoded myself into a corner ;-). My understanding of unicode >> has room for improvement, that's for sure. I got some pointers and >> initial code-cleanup seem to have removed some of the strange results I >> got, which several of you also pointed out. >> >> Anyway, thanks for all your replies. I think I can get this thing up >> and running with a bit more code tinkering. And I'll read up on some >> unicode-docs as well. :-) Thanks again. > >I strongly suggest that you read the docs *FIRST*, and don't "tinker" >at all. . . . Does help? From fredrik at pythonware.com Wed Nov 15 12:25:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Nov 2006 18:25:54 +0100 Subject: Yield In-Reply-To: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> References: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> Message-ID: Mateuszk87 wrote: > may someone explain "yield" function, please. how does it actually work > and when do you use it? it returns a value from a function without actually terminating the function; when the function is resumed, it'll continue to execute after the yield. a function that contains a yield statement is called a "generator", and is most often used in a for-in loop, or in other contexts that expect a sequence. the loop is automatically terminated when the function returns in a usual way: >>> def gen(): ... yield 1 ... yield 2 ... yield 3 ... >>> for item in gen(): ... print item ... 1 2 3 >>> sum(gen()) 6 >>> [str(i) for i in gen()] ['1', '2', '3'] you can also use the generator "by hand"; when you call a generator function, it returns a special "generator object", and then immediately suspends itself. to run the generator, call its "next" method: >>> g = gen() >>> g >>> g.next() 1 >>> g.next() 2 >>> g.next() 3 when the generator is exhausted, it raises a StopIterator exception: >>> g.next() Traceback (most recent call last): File "", line 1, in StopIteration reference information: http://effbot.org/pyref/yield.htm hope this helps! From john106henry at hotmail.com Mon Nov 6 12:07:05 2006 From: john106henry at hotmail.com (John Henry) Date: 6 Nov 2006 09:07:05 -0800 Subject: python GUIs comparison (want) In-Reply-To: <1162827467.001209.29600@f16g2000cwb.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <1161783204.875966.164720@b28g2000cwb.googlegroups.com> <1162827467.001209.29600@f16g2000cwb.googlegroups.com> Message-ID: <1162832825.037508.179770@m73g2000cwd.googlegroups.com> Yes, from a easy of use standpoint, I agree that PythonCard is very high on the list. Unfortunately there isn't more "activities" as one would like to see. On the other hand, that's typical of open-source projects. We can always roll up our sleeves and do it ourselves. At least the multicolumn control isn't particularly complex, should be able to figure out from the source code how to sort. I believe I did that some time ago. I believe I ended up reshuffling the list... metaperl wrote: > rdsteph at mac.com wrote: > > Paul Boddie wrote: > > > > """The figures behind the scenes are quite enlightening for that > > particular page. If you (or community experiences) don't agree with the > > > > rankings (wxPython apparently even easier to learn than PythonCard and > > Tinder, a bunch of Gtk-based toolkits having more or less "full" Linux > > scores) then you'll have some surprises, I'm sure. Nevertheless, it's > > an interesting concept. """ > > > > Well, I don't know what I was thinking, exactly, when I rated > > PythonCard's ease of use...so I went back and changed it to rate it a > > lot higher. The ratings in this script were done a long time ago now > > I dropped Pythoncard when I could not sort multi column lists and when > I posted to the email list and no one answered me. > > But prior to that it was great. From anthony at python.org Wed Nov 1 05:50:32 2006 From: anthony at python.org (Anthony Baxter) Date: Wed, 1 Nov 2006 21:50:32 +1100 Subject: RELEASED Python 2.3.6, FINAL Message-ID: <200611012150.44644.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.3.6 (FINAL). Python 2.3.6 is a security bug-fix release. While Python 2.5 is the latest version of Python, we're making this release for people who are still running Python 2.3. Unlike the recently released 2.4.4, this release only contains a small handful of security-related bugfixes. See the website for more. * Python 2.3.6 contains a fix for PSF-2006-001, a buffer overrun * in repr() of unicode strings in wide unicode (UCS-4) builds. * See http://www.python.org/news/security/PSF-2006-001/ for more. This is a **source only** release. The Windows and Mac binaries of 2.3.5 were built with UCS-2 unicode, and are therefore not vulnerable to the problem outlined in PSF-2006-001. The PCRE fix is for a long-deprecated module (you should use the 're' module instead) and the email fix can be obtained by downloading the standalone version of the email package. Most vendors who ship Python should have already released a patched version of 2.3.5 with the above fixes, this release is for people who need or want to build their own release, but don't want to mess around with patch or svn. There have been no changes (apart from the version number) since the release candidate of 2.3.6. Python 2.3.6 will complete python.org's response to PSF-2006-001. If you're still on Python 2.2 for some reason and need to work with UCS-4 unicode strings, please obtain the patch from the PSF-2006-001 security advisory page. Python 2.4.4 and Python 2.5 have both already been released and contain the fix for this security problem. For more information on Python 2.3.6, including download links for source archives, release notes, and known issues, please see: http://www.python.org/2.3.6 Highlights of this new release include: - A fix for PSF-2006-001, a bug in repr() for unicode strings on UCS-4 (wide unicode) builds. - Two other, less critical, security fixes. Enjoy this release, Anthony Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From do-not-reply at by-mail.com Fri Nov 17 05:18:41 2006 From: do-not-reply at by-mail.com (Johan von Boisman) Date: Fri, 17 Nov 2006 11:18:41 +0100 Subject: A question on Encoding and Decoding. In-Reply-To: <1163584122.966665.149360@k70g2000cwa.googlegroups.com> References: <1163443052.228761.318200@h54g2000cwb.googlegroups.com> <1163584122.966665.149360@k70g2000cwa.googlegroups.com> Message-ID: rbsharp at gmx.de wrote: > Hello, > I think this remark is more to the point. In my experience, the general > problem is that python operates with the default encoding "ascii" as in > sys.getdefaultencoding(). It is possible to set the defaultencoding in > sitecustomize.py, with sys.setdefaultencoding('latin1'). I have placed > sitecustomize.py in Lib/site-packages. It is not possible to set the > encoding once python has started. Setting the encoding only works if > you can bind yourself to this one encoding and is therefore no general > fix. > The only reasonable way to work is to get your strings into unicode > (and sometimes back out again). > If for instance you type: > s = "???????" and then try > us = unicode(s) you will get a traceback identical to yours. I missed the beginning of this thread, but why not write s = u"???????" Is there ever a reason _not_ to exclusively use the unicode stringtype throughout your Python program? (of course you may need to encode/decode when interfacing with the world outside your program) /johan From skip at pobox.com Wed Nov 8 16:35:36 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 8 Nov 2006 15:35:36 -0600 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: <45524A1A.5090407@mvista.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> <1163011320.632781.53370@m7g2000cwm.googlegroups.com> <45522C3E.3050705@mvista.com> <17746.17512.702626.550949@montanaro.dyndns.org> <45524A1A.5090407@mvista.com> Message-ID: <17746.19880.389526.821294@montanaro.dyndns.org> Carl> As for your statement about how "command of the language" (in Carl> reference to python) extends to written/spoken word, I don't quite Carl> understand what you are saying. Just that posts to newsgroups like c.l.py are examples of your written prose, profane or not. Carl> Can you explain how the use of profanity affects one's ability to Carl> code in python or explain their code? I've been programming for 20 some-odd years. I've found that spoken and written communication skills have always been as important to success as pure programming skills. Skip From johnjsal at NOSPAMgmail.com Thu Nov 9 10:27:18 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 09 Nov 2006 10:27:18 -0500 Subject: Can not download plugins for jEdit (help!!) In-Reply-To: <1163078175.600579.22930@h54g2000cwb.googlegroups.com> References: <1163055167.418011.236870@h48g2000cwc.googlegroups.com> <1163066294.697993.148680@h48g2000cwc.googlegroups.com> <1163078175.600579.22930@h54g2000cwb.googlegroups.com> Message-ID: <45534800$0$12978$c3e8da3@news.astraweb.com> Ant wrote: > I do use vim more than Python these days What does that mean? Are you referring to all the setup involved with vim? From dimitri.pater at gmail.com Wed Nov 8 06:02:31 2006 From: dimitri.pater at gmail.com (dimitri pater) Date: Wed, 8 Nov 2006 12:02:31 +0100 Subject: Python deployment options. In-Reply-To: <1162982262.010438.99260@f16g2000cwb.googlegroups.com> References: <1162982262.010438.99260@f16g2000cwb.googlegroups.com> Message-ID: Hi, try: http://www.py2exe.org/ regards, Dimitri On 8 Nov 2006 02:37:42 -0800, king kikapu wrote: > > > Hi to all folks here, > > i just bought a book and started reading about this language. > I want to ask what options do we have to deploy a python program to > users that do not have the labguage installed ?? > > I mean, can i make an executable file, or something that contains the > runtime and the modules that the program only use or am i forced to > download the language to the user machine so the .py files can be run > ?? > > Thanks in advance, > > king kikapu > > -- > http://mail.python.org/mailman/listinfo/python-list > -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From olsongt at verizon.net Wed Nov 8 13:23:23 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 8 Nov 2006 10:23:23 -0800 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: <1163000984.575289.87230@i42g2000cwa.googlegroups.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> <4551FA0F.4000202@hotmail.com> <1163000984.575289.87230@i42g2000cwa.googlegroups.com> Message-ID: <1163010203.489775.308950@b28g2000cwb.googlegroups.com> BartlebyScrivener wrote: > Chaz Ginger wrote: > > >> it is supposed to be about PYTHON. Get it? > > I agree. And Python is an extremely serious matter calling for decorum > and propriety. > > Don't say fuck, ni, peng, or ni-wom. > > http://en.wikipedia.org/wiki/Knights_who_say_Ni > > rd Does using foobar in examples count as profanity? http://en.wikipedia.org/wiki/Foobar From pavlovevidence at gmail.com Fri Nov 24 11:12:53 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 24 Nov 2006 08:12:53 -0800 Subject: Newbie Developing a Python Extension In-Reply-To: References: Message-ID: <1164384773.152649.296600@f16g2000cwb.googlegroups.com> Jeremy wrote: > Hi, > > I have been working on Linux 2.6.9 to adapt a C++ module to work as a Python > extension with the following setup.py file: > > from distutils.core import setup, Extension > > sm=Extension( > 'tdma', > define_macros=[('__USE_POSIX199309','1')], > include_dirs=['/usr/include','/usr/include/python2.3'], > library_dirs=['/usr/lib'], > sources=['Bitstrea.cpp','bytequeu.cpp','debug.cpp','dlist.cpp', > 'GrPort.cpp','IoPort.cpp','LMEmu.cpp','LMEmuPdu.cpp', > 'MacPyIf.cpp','per_os_clk.cpp','timer.cpp']) > > setup(name='MySm', > version='0.1.0', > description='TDMA MAC', > ext_modules=[sm]) > > The extension uses the POSIX call clock_gettime() and things seem fine when > generating the tdma.so file. However, when running the Python program, at a > line 'from tdma import init,txdn,txup,...', I get an error message saying > 'ImportError: /home/.../tdma.so: undefined symbol: clock_gettime'. You're missing a library. From the clock_gettime man page: NOTE Most systems require the program be linked with the librt library to use these functions. So you need to build the extention with librt. Try adding a 'libraries = ['rt']' option to the extension definition. (Unfortunately, on Linux, builduing a shared object without specifying libraries needed passes silently. It'd be nice if there was an option to require all undefined non-Python symbols to be accounted for by some library, but that would be a lot of work to implement.) Carl Banks From skip at pobox.com Fri Nov 10 12:54:39 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 10 Nov 2006 11:54:39 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <45538b0d$0$26485$c3e8da3@news.astraweb.com> <17748.35935.368749.950252@montanaro.dyndns.org> Message-ID: <17748.48351.853342.505257@montanaro.dyndns.org> Robert> skip at pobox.com wrote: >> P.S. I felt I just had to tie this into the thread on profanity somehow. >> But notice that I didn't mention nazis or Hitler. ;-) Robert> You did it just now! Hence the smiley. ;-) S From bnblazer at gmail.com Wed Nov 8 13:01:44 2006 From: bnblazer at gmail.com (Brian) Date: 8 Nov 2006 10:01:44 -0800 Subject: Strange re problem on OSX but Not Linux Message-ID: <1163008904.817018.186000@h54g2000cwb.googlegroups.com> I have a very small script: import re text = open('eq.txt','r').read() regex = '[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]' pattern = re.compile(regex) match = pattern.findall(text) print ''.join(match) However, when I try to run it, I get this error: Traceback (most recent call last): File "/Applications/Komodo.app/Contents/SharedSupport/dbgp/bin/pydbgp", line 66, in import dbgp.client File "/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", line 44, in import traceback, re File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 5, in # AttributeError: 'module' object has no attribute 'compile' ------------------------------------------------------------------------------- Here is the error outside of Komodo: Traceback (most recent call last): File "reg1.py", line 1, in import re File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 5, in # AttributeError: 'module' object has no attribute 'compile' ------------------------------------------------------------------------------ This is running 2.5 on my OSX box. If I run it (again with 2.5) on my SUSE machine, I get no errors. I am sure that I have overlooked something trivial here - so please be gentle if it is on the stupid side of things. Thanks, Brian From carsten at uniqsys.com Thu Nov 2 15:46:20 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 02 Nov 2006 15:46:20 -0500 Subject: what's the difference between these two methods? (aka, why doesn't one of them work?) In-Reply-To: <1162499293.080529.5480@m73g2000cwd.googlegroups.com> References: <1162499293.080529.5480@m73g2000cwd.googlegroups.com> Message-ID: <1162500380.9422.9.camel@dot.uniqsys.com> On Thu, 2006-11-02 at 12:28 -0800, JohnJSal wrote: > Can someone explain to me why the first version of this method works, > but the second one doesn't? All I've changed (I think) is how the > information is nested. The error I'm getting is that the call to > xrc.XRCCTRL is not working in the second example. Instead of getting > the appropriate widget, it's returning None. Is this a result of the > nesting, or the for loops perhaps? > [...] > Traceback (most recent call last): > File "C:\Python25\myscripts\labdb\dbapp.py", line 91, in OnSaveRecord > table_values.append(xrc.XRCCTRL(tab, textfield_id).GetValue()) > AttributeError: 'NoneType' object has no attribute 'GetValue' > You might find it helpful to inspect (e.g. print) textfield_id before the line that causes the exception. -Carsten From frank at chagford.com Tue Nov 7 00:20:15 2006 From: frank at chagford.com (Frank Millman) Date: 6 Nov 2006 21:20:15 -0800 Subject: sqlite error? In-Reply-To: <454faf0a$0$12993$c3e8da3@news.astraweb.com> References: <454fa4dc$0$6987$c3e8da3@news.astraweb.com> <1162849478.092439.297160@i42g2000cwa.googlegroups.com> <454faf0a$0$12993$c3e8da3@news.astraweb.com> Message-ID: <1162876815.281902.70620@e3g2000cwe.googlegroups.com> John Salerno wrote: > >> Am I using the ? placeholder wrong in this example? > >> > >> > >> t = ('hi', 'bye') > >> > >> self.connection.execute("INSERT INTO Personal (firstName, lastName) > >> VALUES ?", t) > >> [snip] > > Thanks guys. I'll try this. I thought the ? stood for the whole tuple. Definitely not. You could have a sql command like this - cur.execute("UPDATE table SET col1 = ?, col2 = ? WHERE col3 = ? AND col4 = ?",(1,2,3,4)) The parameters could be scattered throughout the command. Therefore the substitution is one-for-one from left to right using the values in the tuple. Frank Millman From geskerrett at hotmail.com Wed Nov 8 06:48:37 2006 From: geskerrett at hotmail.com (geskerrett at hotmail.com) Date: 8 Nov 2006 03:48:37 -0800 Subject: struggling with memory release using ctypes wrapper In-Reply-To: <1162957336.662745.243560@m7g2000cwm.googlegroups.com> References: <1162957336.662745.243560@m7g2000cwm.googlegroups.com> Message-ID: <1162986517.575072.105480@m7g2000cwm.googlegroups.com> Oops, found the problem in my code. Sorry for wasting peoples time if you're viewing. From paddy3118 at netscape.net Sat Nov 18 02:01:07 2006 From: paddy3118 at netscape.net (Paddy) Date: 17 Nov 2006 23:01:07 -0800 Subject: basic python questions References: <1163829271.660193.70450@j44g2000cwa.googlegroups.com> Message-ID: <1163833267.823022.107680@f16g2000cwb.googlegroups.com> nateastle at gmail.com wrote: > I have a simple assignment for school but am unsure where to go. The > assignment is to read in a text file, split out the words and say which > line each word appears in alphabetical order. I have the basic outline > of the program done which is: > > def Xref(filename): > try: > fp = open(filename, "r") > lines = fp.readlines() > fp.close() > except: > raise "Couldn't read input file \"%s\"" % filename > dict = {} > for line_num in xrange(len(lines)): > if lines[line_num] == "": continue > words = lines[line_num].split() > for word in words: > if not dict.has_key(word): > dict[word] = [] > if line_num+1 not in dict[word]: > dict[word].append(line_num+1) > return dict > > My question is, how do I easily parse out punction marks and how do I > sort the list and if there anything else that I am doing wrong in this > code it would be much help. Hi, on first reading, you have a naked except clause that catches all exceptions. You might want to try your program on a non-existent file to find out the actual exception you need to trap for that error message. Do you want the program to continue if you have no input file? If you have not covered Regular Expressions, often called RE's then one way of getting rid of puctuation is to turn the problem on its head. create a string of all the characters that you consider as valid in words then go through each input line discarding any character not *in* the string. Use the doctored line for word extraction. help(sorted) will start you of on sorting in python. Other documentation sources have a lot more. P.S. I have not run the code myself P.P.S. Where is the functions docstring! P.P.P.S. You might want to read up on enumerate. It gives another way to do things when you want an index as well as each item from an iterable but remember, the index given starts from zero. Oh, and welcome to comp.lang.python :-) - Paddy. From david at boddie.org.uk Thu Nov 9 11:06:52 2006 From: david at boddie.org.uk (David Boddie) Date: 9 Nov 2006 08:06:52 -0800 Subject: ANN: PyQt v4.1 Released References: <1162749608.733730.321970@k70g2000cwa.googlegroups.com> <1162817233.695765.22780@b28g2000cwb.googlegroups.com> <1162831146.195927.296110@e3g2000cwe.googlegroups.com> <1163086763.536524.37710@h48g2000cwc.googlegroups.com> Message-ID: <1163088412.025310.185250@m7g2000cwm.googlegroups.com> Tool69 wrote: > > That uses a port of an old syntax highlighting example from Qt 4.0. Someone > needs to "port" the C++ example from Qt 4.2 to PyQt4. > > So, we've got no sample to use QScintilla2 ?? Well, this should get you started: import sys from PyQt4.QtGui import QApplication from PyQt4.Qsci import QsciScintilla, QsciLexerPython if __name__ == "__main__": app = QApplication(sys.argv) editor = QsciScintilla() lexer = QsciLexerPython() editor.setLexer(lexer) editor.show() editor.setText(open("qscintilla2_example.py").read()) sys.exit(app.exec_()) QScintilla provides a selection of different lexers, so you might want to experiment with those. Good luck! David From aboudouvas at panafonet.gr Wed Nov 22 07:50:00 2006 From: aboudouvas at panafonet.gr (king kikapu) Date: 22 Nov 2006 04:50:00 -0800 Subject: Python visual IDE In-Reply-To: <45643e06$0$11154$426a74cc@news.free.fr> References: <1164188410.516169.171150@f16g2000cwb.googlegroups.com> <45643e06$0$11154$426a74cc@news.free.fr> Message-ID: <1164199800.476217.224800@j44g2000cwa.googlegroups.com> hmmm,,,ok, i see your point. As i understand it, as a newcomer, it is a little cumbersome to right the code in one ide, "glue" the UI from another toll and all that stuff. I know it works but if someone is coming from VS.Net, it seems a little strange, at first. I also saw that the wxWidgets is the more "feel natural" in all platforms so i believe that if an IDE is able to offer RAD capabilities and build upon this widget, it will be an awesome tool for Python programmers, matches this way VS and other win RAD IDEs... Thanks a lot for your post, i'll have a look at the programs you mention! King Kikapu On Nov 22, 2:09 pm, Bruno Desthuilliers wrote: > king kikapu wrote: > > Hi to all, > > > i am not sure if this question really belongs here but anyway, here it > > goes: I have seen a lot of IDEs for Python, a lot of good stuff but > > actually none of them has what, for example, Visual Studio has: a > > Visual Editor (with the ability to place controls on forms etc etc), > > or RAD > > > I know that there is Glade but does anybody knows of some product, or > > an ongoing effort to this direction so i can have a look at ? > > > Coming from Windows and vs.net world, i think the only missing point > > here is the integration of the Pyrthon with a RAD IDE... > > > Thanks a lot and i apologize if this isn't the correct place for this > > question...If you use wxWidgets, you may want to have a look at projects like > Boa-constructor or PythonCard. If you use QT/KDE, Eric3 offers good > integration with QT Designer IIRC. > > Now as you can see, the problem with RAD tools is that they are specific > to a given GUI toolkit. Python runs on a lot of platforms, and some of > these platforms (ie Linux) are not tied to a specific GUI toolkit. So > integrating the RAD tool in the IDE means you can't use this IDE with > other GUI toolkits. > > Also, there's a tradition in the *n*x world about preferring small, > highly specialized tools over huge monolithic do-it-all applications. As > an example, I daily use half a dozen languages, and I wouldn't like to > have to learn half a dozen IDEs. I'm much more productive with a good > code editor, the command line, and a few external tools when needed. > > My 2 cents... > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'on... at xiludom.gro'.split('@')])"- Hide quoted text -- Show quoted text - From python.list at tim.thechases.com Tue Nov 21 09:33:37 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 21 Nov 2006 08:33:37 -0600 Subject: Vim scripts for editing Python? In-Reply-To: <1164117947.465994.246510@k70g2000cwa.googlegroups.com> References: <1164086261.774376.125490@j44g2000cwa.googlegroups.com> <1164089307.390351.263980@j44g2000cwa.googlegroups.com> <1164117947.465994.246510@k70g2000cwa.googlegroups.com> Message-ID: <45630E41.5080205@tim.thechases.com> > For example, to auto-fold all function bodies while leaving > the function names visible. Do you mean :set foldmethod=indent which does what I think you're describing... > Also to auto-close braces like [], (), {}, autoclose quotes. You can map whatever you like: :inoremap [ [] :inoremap ( () :inoremap { {} :inoremap " "" :inoremap ' '' which will do the trick for you. As for the other things, I haven't monkeyed with them, but if you drop by the vim mailing list, there are other smart cookies there that can help you out. I've heard of such abilities...just haven't played with them. -tkc From mail at microcorp.co.za Thu Nov 23 02:14:54 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 23 Nov 2006 09:14:54 +0200 Subject: Tkinter, main loop question. References: <1164248529.501106.255990@e3g2000cwe.googlegroups.com> Message-ID: <020001c70ecf$3ac42260$03000080@hendrik> "Exod" wrote: > Don't know if its possible in this light-weight GUI toolset, but can i > somehow hook up into the mainloop in it, for example if i were to > create an internet application, i would need to keep recieving data > from within it? Its possible - use the call back mechanism to implement a ticker or stutter thread, remembering that you cant block here, because then the gui stops. If its a good idea is another question, because sockets wants to be the main thread too. but if you fire up another process for the comms, and use threads in front of pipes, with queues to the ticker in the main loop, it works. Just don't call any gui stuff from threads in the same process, only from the ticker or stutter thread. - Hendrik From john106henry at hotmail.com Fri Nov 17 14:48:36 2006 From: john106henry at hotmail.com (John Henry) Date: 17 Nov 2006 11:48:36 -0800 Subject: remove a list from a list In-Reply-To: <1163792832.404528.187950@k70g2000cwa.googlegroups.com> References: <455E0A20.9000509@tim.thechases.com> <1163792832.404528.187950@k70g2000cwa.googlegroups.com> Message-ID: <1163792916.095832.259010@m73g2000cwd.googlegroups.com> Scratch that. b becomes all upper... John Henry wrote: > from sets import Set as set # Python 2.3 > > b = list( set([i.upper() for i in b) - set([i.upper() for i in a] ) ) > > > Rares Vernica wrote: > > Yeah, I ended up doing a similar kind of loop. That is pretty messy. > > > > Is there any other way? > > > > Thanks, > > Ray > > > > Tim Chase wrote: > > >> That is a nice solution. > > >> > > >> But, how about modifying the list in place? > > >> > > >> That is, l would become ['c', 'D']. > > >> > > >>> >>> e = ['a', 'b', 'e'] > > >>> >>> l = ['A', 'a', 'c', 'D', 'E'] > > >>> >>> s = set(e) > > >>> >>> [x for x in l if x.lower() not in s] > > >>> ['c', 'D'] > > > > > > > > > Well...changing the requirements midstream, eh? ;-) > > > > > > You can just change that last item to be a reassignment if "l" is > > > all you care about: > > > > > > >>> l = [x for x in l ...] > > > > > > Things get a bit hairier if you *must* do it in-place. You'd > > > have to do something like this (untested) > > > > > > for i in xrange(len(l), 0, -1): > > > if l[i-1].lower() in s: > > > del l[i-1] > > > > > > > > > which should do the job. > > > > > > -tkc > > > > > > > > > From billjosephson at hotmail.com Thu Nov 9 01:52:47 2006 From: billjosephson at hotmail.com (BillJosephson) Date: 8 Nov 2006 22:52:47 -0800 Subject: Can not download plugins for jEdit (help!!) Message-ID: <1163055167.418011.236870@h48g2000cwc.googlegroups.com> Hi all. I am trying to use jEdit, but can't seem to download any plugins. I go to Plugin Manager, and select Download options. I update the mirro and can see lots of servers. I select the first (plugin central default) and say apply. In the Update dialogues bottom window, I see a msg saying "Dowloading plugin list from jedit.plugins.org but after a couple seconds it disappears. Inveitably when I select Console and the click install, it give me "An I/0 error occurred (Connection refused: connect) If anyone knows why i can't connect, in info about it would be a big help. Thanks in advance..... From korvus at gmail.com Thu Nov 16 19:48:29 2006 From: korvus at gmail.com (Jeff Poole) Date: 16 Nov 2006 16:48:29 -0800 Subject: cPickle problems In-Reply-To: <1163723175.530850.185990@m73g2000cwd.googlegroups.com> References: <1163722893.992949.295350@b28g2000cwb.googlegroups.com> <1163723175.530850.185990@m73g2000cwd.googlegroups.com> Message-ID: <1163724509.572724.199720@f16g2000cwb.googlegroups.com> To clutter this up with yet another message, this is what happens if I use pickle instead of cPickle. Same error, but it has more of a stack trace so someone more advanced than myself might be able to pick out what is going amiss. Traceback (most recent call last): File "./generateTools.py", line 50, in ? proj.findVHDLfiles("vhd") File "/cygdrive/c/fpga/tools/FPGAProject.py", line 631, in findVHDLfiles cpickle.dump(filenameToClassDic,pickleFile,PICKLE_FILE_PROTOCOL) File "/usr/lib/python2.4/pickle.py", line 1382, in dump Pickler(file, protocol, bin).dump(obj) File "/usr/lib/python2.4/pickle.py", line 231, in dump self.save(obj) File "/usr/lib/python2.4/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python2.4/pickle.py", line 663, in save_dict self._batch_setitems(obj.iteritems()) File "/usr/lib/python2.4/pickle.py", line 677, in _batch_setitems save(v) File "/usr/lib/python2.4/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/usr/lib/python2.4/pickle.py", line 433, in save_reduce save(state) File "/usr/lib/python2.4/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python2.4/pickle.py", line 663, in save_dict self._batch_setitems(obj.iteritems()) File "/usr/lib/python2.4/pickle.py", line 677, in _batch_setitems save(v) File "/usr/lib/python2.4/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python2.4/pickle.py", line 614, in save_list self._batch_appends(iter(obj)) File "/usr/lib/python2.4/pickle.py", line 629, in _batch_appends save(x) File "/usr/lib/python2.4/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python2.4/pickle.py", line 576, in save_tuple save(element) File "/usr/lib/python2.4/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/usr/lib/python2.4/pickle.py", line 433, in save_reduce save(state) File "/usr/lib/python2.4/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/usr/lib/python2.4/pickle.py", line 663, in save_dict self._batch_setitems(obj.iteritems()) File "/usr/lib/python2.4/pickle.py", line 677, in _batch_setitems save(v) File "/usr/lib/python2.4/pickle.py", line 313, in save rv = reduce(self.proto) File "/usr/lib/python2.4/copy_reg.py", line 83, in _reduce_ex dict = getstate() TypeError: 'str' object is not callable Jeff Poole wrote: > Oh, and I suppose I should provide some version information: > > $ python > Python 2.4.3 (#1, May 18 2006, 07:40:45) > [GCC 3.3.3 (cygwin special)] on cygwin > > > Jeff Poole wrote: > > This is going to be a pretty vague message because it involves a large > > block of code I'd rather avoid posting. Basically, I've been pickling > > a dictionary of instances of a class I've created (which contains > > references to other instances of other classes). At some point in the > > last few weeks, pickling has stopped working with the following error: > > > > Traceback (most recent call last): > > File "./generateTools.py", line 50, in ? > > proj.findVHDLfiles("vhd") > > File "/cygdrive/c/fpga/tools/FPGAProject.py", line 630, in > > findVHDLfiles > > cpickle.dump(filenameToClassDic,pickleFile,PICKLE_FILE_PROTOCOL) > > File "/usr/lib/python2.4/copy_reg.py", line 83, in _reduce_ex > > dict = getstate() > > TypeError: 'str' object is not callable > > > > > > Does anyone have any idea why this might be failing in this way? It's > > driving me crazy. If need be I can probably provide the code to the > > class, though it's about 1000 lines, most of which is PyParsing code. > > I appreciate any help you guys can provide. > > > > > > Jeff From metalzong at 163.com Thu Nov 30 03:02:31 2006 From: metalzong at 163.com (Metal Zong) Date: Thu, 30 Nov 2006 16:02:31 +0800 Subject: [help] Is it true to call obj.__str__() while executing "printobj"? In-Reply-To: <76fd5acf0611291809n6317e159j4d255dafabbda177@mail.gmail.com> Message-ID: <456E93DA.009A9C.11690> Thanks. Please refer to following snipt: 1 >>> class Printable(type): 2 ... def __str__(cls): 3 ... return "This is class %s" % cls.__name__ 4 ... 5 >>> class C(object): 6 ... __metaclass__ = Printable 7 ... 8 >>> 9 >>> C.__str__ 10 11 >>> 12 >>> print C 13 This is class C I see, name resolving will follow instance, bases (determined by meta-method mro() ), the last is it's metaclasse. Hence, line 10 shows the " slot wrapper '__str__' of 'object' objects" by I was surprised when I saw line 13 - "print" statement calls str() and the latter one calls obj.__str__() but it seems "obj.__str__" is different from "obj.__str__()" and I was confused by this difference. - Tommy -----Original Message----- From: python-list-bounces+metalzong=163.com at python.org [mailto:python-list-bounces+metalzong=163.com at python.org] On Behalf Of Calvin Spealman Sent: Thursday, November 30, 2006 10:09 AM To: tzong at sigma-rt.com; python-list at python.org Subject: Re: [help] Is it true to call obj.__str__() while executing "printobj"? On 11/29/06, Tommy Zong wrote: > > > > > > > Hi, > > > > I am learning metaclass by reading "Metaclass programming in Python, Part > 2". I have a question as following and had tried to search from internet and > also have read the article "Unifying types and classes in Python 2.2" but > failed to get satisfied answer. Could you please give me any comments to > enlighten me? Thank you very much. > > > > {{{ > > # > > # inheritance inheritance > > # object -------------> type -------------> Printable(Printable.__str__) > > # | . > > # | . > instantiation > > # | . > > # | v > > # ----------------------------------------> C(?) > > # . > > # . > instantiation > > # . > > # v > > # c(?) > > # > > >>> class Printable(type): > > ... def __str__(cls): > > ... return "This is class %s" % cls.__name__ > > ... > > >>> class C(object): > > ... __metaclass__ = Printable > > ... > > >>> print C # > equivalent to print Printable.__str__(C) > > This is class C > > >>> c = C() > > >>> print c # > equivalent to print C.__str__(c) > > <__main__.C object at 0x1870dacc> > > > > >>> C.__str__ > > > > >>> print C > > This is class C > > }}} > > > > The question is why Printable.__str__ is invoked while executing "print C" > but "C.__str__" shows it is resolved as "objct.__str__"? > > > > Wish I can get reply from you. Really thanks. > > > > Best Regards, > > > Tommy Zong > Chengdu Jiehua Technologies Co, Ltd. > Tel: 86-28-85148500-654 > Mail: tzong at sigma-rt.com > MSN: metalzong at 163.com > -- > http://mail.python.org/mailman/listinfo/python-list > > You are defining a metaclass, a class, and an instance of this class. You are defining a method in the metaclass. When the name is looked up on any object, if the object has no attribute of that name (no __str__ in this case) the search moves to its type, and from there to each type in the MRO (method resolution order). When you follow through the lookup rules, from object to type to supertypes, you see that none of the metaclasses for any of the classes in your object's MRO comes into play. Those are types of the types. They come into play when you lookup an attribute on the types themselves only, not on the instances of those types. That is why you see the bahavior you do. Of course, it wouldnt make sense for this method to be used with the instances, because they aren't classes, so the message would be incorrect. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Tue Nov 28 13:49:48 2006 From: sjmachin at lexicon.net (John Machin) Date: 28 Nov 2006 10:49:48 -0800 Subject: How to increase the speed of this program? In-Reply-To: References: <1164699156.682944.97410@j44g2000cwa.googlegroups.com> <1164706548.778583.267730@n67g2000cwd.googlegroups.com> <1164714786.086910.288450@45g2000cws.googlegroups.com> Message-ID: <1164739788.335821.239100@n67g2000cwd.googlegroups.com> Fredrik Lundh wrote: > John Machin wrote: > > > I'm extremely agnostic about the spelling :-) IOW I'd be very glad of > > any way [pure Python; e.g. maintaining my own version of the array > > module doesn't qualify] to simply and rapidly create an array.array > > instance with typecode t and number of elements n with each element > > initialised to value v (default to be the zero appropriate to the > > typecode). > > array(t, [v])*n > > Thanks, that's indeed faster than array(t, [v]*n) but what I had in mind was something like an additional constructor: array.filledarray(typecode, repeat_value, repeat_count) which I speculate should be even faster. Looks like I'd better get a copy of arraymodule.c and start fiddling. Anyone who could use this? Suggestions on name? Argument order? Functionality: same as array.array(typecode, [repeat_value]) * repeat_count. So it would cope with array.filledarray('c', "foo", 10) I'm presuming an additional constructor would be better than doubling up on the existing one: array.array(typecode[, initializer) and array.array(typecode[, repeat_value, repeat_count]) Cheers, John From gabrielg_laburando at yahoo.com.ar Wed Nov 8 13:27:45 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Wed, 08 Nov 2006 15:27:45 -0300 Subject: unpickling Set as set In-Reply-To: <1162974390.329872.170540@e3g2000cwe.googlegroups.com> References: <1162967110.642248.54400@m7g2000cwm.googlegroups.com> <1162968716.356479.124850@m7g2000cwm.googlegroups.com> <1162974390.329872.170540@e3g2000cwe.googlegroups.com> Message-ID: <7.0.1.0.0.20061108152041.05a6cda8@yahoo.com.ar> At Wednesday 8/11/2006 05:26, George Sakkis wrote: >Or you may have this done automatically by hacking the Set class: > >from sets import Set >import cPickle as pickle > >Set.__reduce__ = lambda self: (set, (self._data,)) > >s = Set([1,2,3]) >x = pickle.dumps(s) >print pickle.loads(x) > > >This doesn't work though if you have already pickled the Set before >replacing its __reduce__, so it may not necessarily be what you want. >If there is a way around it, I'd like to know it. Perhaps registering a suitable reduce function in the copy_reg module. If the sets were pickled alone, and it's not too much trouble, using: a_set = set(a_set) just after unpickling may be enough. And if they were instance attributes, __setstate__ on the class can do the conversion. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From thn at mail.utexas.edu Thu Nov 2 01:00:02 2006 From: thn at mail.utexas.edu (Thomas Nelson) Date: 1 Nov 2006 22:00:02 -0800 Subject: can I import the module twice (under differnet names) In-Reply-To: References: Message-ID: <1162447202.188282.240440@h48g2000cwc.googlegroups.com> alf wrote: > Hi, > > wonder if in the python I could treat modules imorts like classes > instances. It means I could import it twice or more times under > different names. > > -- > alfz1 You can always give any object as many names as you want: >>> import sys >>> s1 = sys >>> s2 = sys >>> s1.path ['', '/usr/local/bin', '/bin', '/sbin', '/usr/bin', '/usr/sbin',... >>> s2.argv [''] Or maybe you're looking for the builtin function reload? >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. ... >>> import this #note nothing happens >>> reload(this) #runs again The Zen of Python, by Tim Peters Beautiful is better than ugly. .... Neither one of these methods are too common in practice I think. Could you tell us why you want to import a module more than once? -Tom From onurb at xiludom.gro Wed Nov 22 06:54:22 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 22 Nov 2006 12:54:22 +0100 Subject: Trying to understand Python objects In-Reply-To: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> Message-ID: <45643a6f$0$7761$426a74cc@news.free.fr> walterbyrd wrote: > Reading "Think Like a Computer Scientist" I am not sure I understand > the way it describes the way objects work with Python. > > 1) Can attributes can added just anywhere? I create an object called > point, then I can add attributes any time, and at any place in the > program? Apart from a few special cases (mainly builtin types or new-style classes using slots IIRC), yes. Now wether this is a good idea is another question. As far as I'm concerned, I do use this feature, but only for special cases, and almost only in metaclasses or other special 2-stages init. > 2) Are classes typically created like this: > > class Point: > pass > > Then attributes are added at some other time? Nope. The canonical idiom is to use the initializer: class Point(object): def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 self.attr3 = 42 > 3) What is with the __underscores__ ?? "magic" methods or attributes. The initializer ('__init__') is one of them, which is called at instance creation time. Most of the magic __methods__ are used to implement or override operators. You'll find the relevant documentation around here: http://docs.python.org/ref/specialnames.html > 4) Are parameters passed to an class definition? > > class Whatever(params): > pass A class statement is not a function definition statement. Here, you ask for a class Whatever inheriting from class params. Cf the above point about the __init__ method for passing args at instanciation. > I sort-of understand the way objects work with PHP. With PHP, the > classes are defined in one place - sort of like a function. FWIW, Python's classes actually are callable objects (just like functions are callable objects). To instanciate a class, you just call the class, no 'new' keyword needed. > To me, that > makes more sense. name = "toto"; echo $obj->name; ?> Just like Python (and Javascript FWIW), PHP objects are mostly hashtable in disguise. But - having some experience with both PHP and Python (and some other OOPLs), I can tell you that Python's object model is far superior to PHP's one. The only "gotcha" here wrt/ most other object models is that attributes defined in the class statement body (ie, outside methods) are attached to the class object itself (and then shared by all instances of the class), not to instances themselves. Instance attributes initialisation is usually done in the __init__(self, ...) method. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From matthiaswinterland at web.de Thu Nov 9 17:36:20 2006 From: matthiaswinterland at web.de (Matthias Winterland) Date: Thu, 09 Nov 2006 23:36:20 +0100 Subject: Simple question to split Message-ID: <4rhov8Frk45nU1@mid.uni-berlin.de> Hi, I have a simple question. When I read in a string like: a='1,2,3,4,5 6 7,3,4', can I get the list l=[1,2,3,4,5,6,7,3,4] with a single split-call? Thx, Matthias From Leo.Kislov at gmail.com Fri Nov 10 18:18:52 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 10 Nov 2006 15:18:52 -0800 Subject: comparing Unicode and string In-Reply-To: References: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> <1161281095.174018.223790@f16g2000cwb.googlegroups.com> <1161595714.342067.51350@e3g2000cwe.googlegroups.com> <1163120577.369133.279080@h48g2000cwc.googlegroups.com> Message-ID: <1163200732.438155.306400@m73g2000cwd.googlegroups.com> Neil Cerutti wrote: > On 2006-11-10, Steve Holden wrote: > >>> But I don't insist on my PEP. The example just shows just > >>> another pitfall with Unicode and why I'll advise to any > >>> beginner: Never write text constants that contain non-ascii > >>> chars as simple strings, always make them Unicode strings by > >>> prepending the "u". > >> > >> That doesn't do any good if you aren't writing them in unicode > >> code points, though. > > > > You tell the interpreter what encoding your source code is in. > > It then knows precisely how to decode your string literals into > > Unicode. How do you write things in "Unicode code points"? > > for = u"f\xfcr" Unless you're using unicode unfriendly editor or console, u"f\xfcr" is the same as u"f?r": >>> u"f\xfcr" is u"f?r" True So there is no need to write unicode strings in hexadecimal representation of code points. -- Leo From vmalloc at gmail.com Tue Nov 21 03:53:56 2006 From: vmalloc at gmail.com (Rotem) Date: 21 Nov 2006 00:53:56 -0800 Subject: platform.python_version_tuple Message-ID: <1164099236.485144.20520@e3g2000cwe.googlegroups.com> Hi Everyone, I've been wondering about platform.python_version_tuple API, which is a bit misleading. The fact is that this returns under both python2.4 and 2.5 a list, and not a tuple. This introduces strange semantics, due to __cmp__ on lists and tuples. platform.python_version_tuple() >= ('2', '5') # returns False under python 2.5 platform.python_version_tuple() >= ['2', '5'] # returns True under python 2.5 I believe this should be changed, especially since the word 'tuple' appears in the function name... What do you think? From saml at al.com.au Mon Nov 6 23:23:00 2006 From: saml at al.com.au (Sam Loxton) Date: Tue, 07 Nov 2006 15:23:00 +1100 Subject: Nested Dictionary Sorting Message-ID: <45500A24.2090800@al.com.au> Hi, I am fairly new to the python language and am trying to sort a nested Dictionary of a Dictionary which I wish to sort by value. The dictionary does not have to be restructured as I only need it sorted in this way for printing purposes. The following is an example of my Dictionary printed with 'print dictionary.items()', where '2329513' is the key of the first hash, 'ops' is the key of the second hash and '50.0' is the value of the second hash which I would like to sort by: [('2329513', {'ops': 20.0}), ('2329492', {'ops': '80'}), ('2329490', {'ops': '50'})] I hope to sort these first keys by the value of the 'ops' key from highest to lowest value to give the following result: [('2329492', {'ops': '80'}), ('2329490', {'ops': '50'}), ('2329513', {'ops': 20.0})] Thanks in advance for any help, Sam. From rcs at bgoark.no Fri Nov 17 20:20:37 2006 From: rcs at bgoark.no (baalbek) Date: Sat, 18 Nov 2006 02:20:37 +0100 Subject: explicit self revisited In-Reply-To: References: Message-ID: <455e5fe0$0$8000$c83e3ef6@nn1-read.tele2.net> Peter Maas wrote: > No magic. Just a dot. But perhaps a dot is too tiny. We could take JUST_ME > or ME_AND_BOBBY_MCGEE instead, of course as a reserved keyword followed > by a > dot ;) Why a dot, and not a @, like in Ruby and Perl? I think a dot is a particular bad idea, not the least due to poorer readability of code (and thou shall not underestimate the readability of code!). Baalbek From robin at reportlab.com Thu Nov 9 09:39:27 2006 From: robin at reportlab.com (Robin Becker) Date: Thu, 09 Nov 2006 14:39:27 +0000 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <1163072637.924217.90610@h54g2000cwb.googlegroups.com> References: <1163072637.924217.90610@h54g2000cwb.googlegroups.com> Message-ID: <45533D9F.5020002@chamonix.reportlab.co.uk> Paul Boddie wrote: > My impression is that POSH isn't maintained any more and that work was > needed to make it portable, as you have observed. Some discussions did > occur on one of the Python development mailing lists about the > possibility of using shared memory together with serialisation > representations faster than pickles (which also don't need to be > managed as live objects by Python), and I think that this could be an > acceptable alternative. > ....... your impression is correct, when I contacted the author some while ago he maintained that it was a proof of concept only. When I compiled this today with python-2.4.2 the example fails with this rather cryptic message ~/devel/posh/examples: $ python Matrix.py Traceback (most recent call last): File "Matrix.py", line 6, in ? import posh File "/usr/local/lib/python2.4/site-packages/posh/__init__.py", line 14, in ? import _core RuntimeError: semaphore set creation failed but that's most likely something to do with not allocating a semaphore of the right sort or something. I think it uses sysv semaphores and although freeBSD 6 has them perhaps there's something I need to do to allow them to work. > Paul > -- Robin Becker From p.lavarre at ieee.org Thu Nov 9 20:03:00 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 9 Nov 2006 17:03:00 -0800 Subject: pack a three byte int References: <1163027401.386603.263030@k70g2000cwa.googlegroups.com> <1163092047.577688.140400@m73g2000cwd.googlegroups.com> <1163114202.636000.234900@m73g2000cwd.googlegroups.com> <1163115840.190634.5800@m73g2000cwd.googlegroups.com> Message-ID: <1163120580.762226.22160@k70g2000cwa.googlegroups.com> > > when talking the 1960's lingo > > ... > > X12Inquiry = 0x12 > > xxs = [0] * 6 > > xxs[0] = X12Inquiry > > xxs[4] = allocationLength > > rq = ''.join([chr(xx) for xx in xxs]) > > It looks wrong (and a few other adjectives), Ah, we agree, thank you for saying. > Looks like little-endian 4-byte integer > followed by 2-byte integer ... what's wrong with struct.pack(" X12Inquiry, allocationLength) ???? Pack ' > skip = 0x123456; count = 0x80 > > hi, lo = divmod(skip, 0x10000) > > Does it do what you asked (one pack call instead of three)???? One pack call, not three, yes. Shatters the 3 byte int into 1 and 2 bytes by divmod of (0xFFFF + 1), yes. > > I guess you're asking me ... > > to show more plainly that indeed I am trying > > to make sense of every word of every answer Am I helping? From fredrik at pythonware.com Fri Nov 3 14:25:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 03 Nov 2006 20:25:08 +0100 Subject: Sorted and reversed on huge dict ? In-Reply-To: <1162580533.981364.211860@h54g2000cwb.googlegroups.com> References: <1162580533.981364.211860@h54g2000cwb.googlegroups.com> Message-ID: vd12005 at yahoo.fr wrote: > i would like to sort(ed) and reverse(d) the result of many huge > dictionaries (a single dictionary will contain ~ 150000 entries). Keys > are words, values are count (integer). not sure 150k entries qualify as huge, though, unless you're short on memory. > i'm wondering if i can have a 10s of these in memory, or if i should > proceed one after the other. why not just try it out? > but moreover i'm interested in saving theses as values, keys sorted and > reversed (ie most frequent first), i can do it with sort from unix > command but i wonder how i should do it with python to be memory > friendly. > > can it be done by using : > > from itertools import izip > pairs = izip(d.itervalues(), d.iterkeys()) > for v, k in reversed(sorted(pairs)): > print k, v > > or will it be the same as building the whole list ? sorted() needs access to all data, so it'll build a list, even if you feed it a generator. you will have to test it yourself, but I suspect that the most memory-efficient way to do what you want could be: items = d.items() items.sort(key=operator.itemgetter(1), reverse=True) the items list would require a couple of megabytes for 150k dictionary entries, or so. the key map needs some memory too, but the rest of the sort is done in place. From martin at v.loewis.de Thu Nov 9 15:02:06 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 09 Nov 2006 21:02:06 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: <1162947569.228388.16940@m7g2000cwm.googlegroups.com> <7xy7qlom0b.fsf@ruckus.brouhaha.com> Message-ID: <4553893e$0$13310$9b622d9e@news.freenet.de> robert schrieb: >>> what about speed. Is it true that IronPython is almost as fast as >>> C-Python meanwhile? > > thus there would be crash if 2 threads use the global variables > (module.__dict__) of a module? IronPython uses the .NET virtual machine. That, in itself, gives consistency guarantees. Read the ECMA IL specification to find out what the consistency model is. Regards, Martin From fredrik at pythonware.com Thu Nov 23 10:22:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Nov 2006 16:22:59 +0100 Subject: ImportError: No module named getopt References: <1164294464.445025.326640@f16g2000cwb.googlegroups.com> Message-ID: "prashant" wrote: >I am running a python script which has the line > > import getopt, sys, os, re, string > > And i get the error > > ImportError: No module named getopt > > Could you please point out a possible solution for this? looks like a broken installation. try running the script as python -vv script.py and see where it looks for the getopt module. is the ImportError all you get, btw ? it doesn't complain about site.py before that ? From ian_stephenson at Sat Nov 4 01:25:14 2006 From: ian_stephenson at (Ian Stephenson) Date: Sat, 4 Nov 2006 17:25:14 +1100 Subject: Converting Microsoft Works databases.... *shudder* References: Message-ID: <12kq0i5akeo8150@corp.supernews.com> I have Works 8.0 and you can SAVE AS to dBase IV format. Not sure for other versions. Regards, Ian "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote in message news:upednTjcPOxtwdbYnZ2dnUVZ_sydnZ2d at comcast.com... >I was wondering if anyone has had any experience with this. Someone I > know is trying to move away from Microsoft Works, and I am trying to > look into a solution that would convert their data in a lossless fashion > to a more modern format. The database has more than 65K rows, so > converting it to be an Excel spreadsheet, would, AFAIK, not be an option. > > It would seem that MS Works can export the database as a DBF format > database, though I have not tried it. Before I get started, I was > wondering if anyone has been through this problem in the past and used > Python to solve the problem. Knowing nearly nothing about the DBase > family of application software, and database formats, I find myself > feeling like the information out there is, frankly, a bit overwhelming. > > Would the recipe specified in the "dbf to csv" thread be useful here for > a file in DBase IV format? It of course uses the same extension, but I > am not sure if the file semantics are at all similar. The idea at the > end would be to probably create a database on an small SQL server (like > MySQL) and let the person access their data using ODBC on their Windows > workstation so that they can create form letters and the like. They do > not have access to MS Office's Access product, nor do they wish to use > OOo Base (and I can't say that I blame them -- it seems to crash far too > often to be considered reliable stuff). > > -- Mike From rrr at ronadam.com Fri Nov 17 18:02:29 2006 From: rrr at ronadam.com (Ron Adam) Date: Fri, 17 Nov 2006 17:02:29 -0600 Subject: Decimal() instead of float? In-Reply-To: <1163800304.5107.179.camel@pepper> References: <1163294604.4675.4.camel@pepper> <1163511997.4675.88.camel@pepper> <4559F828.7070704@holdenweb.com> <1163794251.5107.151.camel@pepper> <1163800304.5107.179.camel@pepper> Message-ID: Michael B. Trausch wrote: > On Fri, 2006-11-17 at 21:25 +0100, Fredrik Lundh wrote: >> > Some of the lat/long pairs that I have used seem to come out fine, but >> > some do not. Because the mathmatics used with them involve complex >> > equations when determining distance and the like, any error gets >> > massively compounded before a final result is evident. >> >> sorry, but I don't think you have the slightest idea what you're doing, >> really. >> > > Sure, I do. Let's say that I want to work with the latitude > 33.6907570. In Python, that number can not be stored exactly without > the aid of decimal.Decimal(). > > >>> 33.6907570 > 33.690756999999998 > >>> > As you can see, it loses accuracy after the 6th decimal place. That's > not good enough: I have 8 numbers that need to be exact, and I am only > getting six. That error will propagate throughout any multiplication or > division problem. The error /compounds/ itself: Actually it doesn't loose accuracy until the final decimal place, which is probably much smaller than the accuracy you need unless you are doing theoretical research on very small time frames with ideal numbers. Then, yes you may need to use either numeric or decimal which can support a much higher precision. Numeric is much faster so I would try that first. On the other hand, if you are writing an application that does practical calculations on real measured data, then you have two sources of errors to be concerned with. One is the unseen error from the actual measurements which is probably much bigger than the error you are trying to avoid. And the other is the minuscule error caused by the binary C representation. For example if a device measures a value of 33.6907570, it is a measurement that can be off by +- 0.0000005 (or more, depending on the accuracy of the device), compared with the error of 0.0000000000000001, it is huge. So if you are not already taking into account the larger error, by rounding your results to a proper number of significant digits, then you may have a much bigger problem, and a much larger real error than you realize. So, you first need to manage the errors introduced when the data is created. By doing that, you will probably find it will also resolve the smaller error you are concerned about here. Cheers, Ron From martin at v.loewis.de Fri Nov 17 20:05:37 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 18 Nov 2006 02:05:37 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: <1163759435.551233.76030@j44g2000cwa.googlegroups.com> References: <455CED78.1060604@v.loewis.de> <455CF4BA.1050608@v.loewis.de> <1163759435.551233.76030@j44g2000cwa.googlegroups.com> Message-ID: <455E5C61.5030502@v.loewis.de> Leo Kislov schrieb: > How about returning two lists, first list contains unicode names, the > second list contains undecodable names: > > files, troublesome = os.listdir(separate_errors=True) > > and make separate_errors=True by default in python 3.0 ? That would be quite an incompatible change, no? Regards, Martin From ptmcg at austin.rr._bogus_.com Sun Nov 19 01:45:28 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 19 Nov 2006 06:45:28 GMT Subject: cPickle problems References: <1163722893.992949.295350@b28g2000cwb.googlegroups.com> <1163723175.530850.185990@m73g2000cwd.googlegroups.com> <1163724509.572724.199720@f16g2000cwb.googlegroups.com> <1163730111.641857.142850@k70g2000cwa.googlegroups.com> Message-ID: "Jeff Poole" wrote in message news:1163730111.641857.142850 at k70g2000cwa.googlegroups.com... > So when something tries to retrieve .__getstate__, it returns an empty > string. If I tell it to raise an AttributeException instead, then I > get this message: > > TypeError: a class that defines __slots__ without defining __getstate__ > cannot be pickled > > I think I need to talk to the author of PyParsing about this one... > Thanks for your help! > > > Jeff Jeff - Sorry not to reply sooner, I have been out of town with limited access to c.l.py. Also, I didn't really pick up on "cPickle problems" as a pyparsing-related post. :) I would be happy to make ParseResults picklable, I didn't realize that this getattr behavior was defeating that capability. I have had people successfully use pickle on pyparsing grammars, but have not had anyone report any pickle experience with ParseResults objects, either pro or con. I have a test version of pyparsing with pickling support added, and it passes my simple unit tests. I could send it to you if you would test it against your program. -- Paul From vatamane at gmail.com Sun Nov 19 04:49:02 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 19 Nov 2006 01:49:02 -0800 Subject: Finding skilled pythonistas for micro-jobs? In-Reply-To: <1163895209.986877.13820@f16g2000cwb.googlegroups.com> References: <1163895209.986877.13820@f16g2000cwb.googlegroups.com> Message-ID: <1163929742.444622.323610@f16g2000cwb.googlegroups.com> If you are agile it means that the developer is in constant communication with the user/client often changing and updating the requirements. The typical work that you specify though is not of that nature because it a list of specifications and then the coder implements it, and when done gets back to you. In other words, you will pay for not having a relationship with the programmer. Theoretically just having the requirements and a set of unit tests should do it, but in practice it might not work, stuff _always_ comes up when you least expect it. Sometimes the clear goals end up not being that clear to both you and a strange new programmer you just met over email. There are other things to consider what if the person doesn't come through? They end up doing something else or forget -- you wait for 3 days, your company expects a result and the programmer you just asked to work for you does not deliver. Or what if they are not satisfied with the pay because it took longer than expected. Also, what would you do about taxes, technically you are employing someone, a day job is still a job. Theoretically one could run a company and never pay the proper taxes because they pay their programmers per day through Paypal... However, you do mention CS students. I would suggest to find a local university and befriend a professor. Then whenever you need a small job ask him. He will know the students (who knows what, how well and so on). Just based on a personal experience from my CS department you will not have a shortage of candidates ( starving graduate students _will_ code for food ), and you get to meet the students in person if you so desire, and then keep them on your contact list. An even better advice -- get two students, you will get a true xp team, they'll have to split the pay but in case one is busy, the other one will be there for you. You can hire them as part time with no benefits and they can put the work on their resume, which will be of great help for them. Note: if your company is well known, you might even find students who will help for free, just so they can put some work experience on their resume... Hope that helps, Nick V. darran wrote: > I'm a partner in a design and technology studio that creates > large-scale interactive exhibits for museums. We are agile - by > choice. For big 6-12 month projects, we try and secure exceptional > python talent on contract. The python job board addresses this need. > > Every few weeks though I run up against a bite-sized programming > problem begging to be farmed out by our small company. The tasks > themselves span the gamut from data wrangling (format conversions) to > SWIG wrappers to Twisted to pyOpenGL. Often the task is 1 or 2 days of > work. Not really big enough to warrant a job search, a contract, or > even someone's full-time attention. The type of problem that is > perfectly suited to a CS student or daytime programmer looking to make > some extra money. Presently, when one of these jobs pops up, I just > add 8-16 hours to my work week - much to the dismay of my 3-year old > daughter who'd rather I pay someone and go to the park. The nice thing > though about our bite-sized jobs is that the goals are perfectly clear > because we are religious in our use of unit testing and test-driven > development. > > Any suggestions then for locating skilled Python/C++ programmers for > these small (micro) jobs? > > Cheers, > Darran. From maxerickson at gmail.com Thu Nov 2 12:47:04 2006 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 2 Nov 2006 17:47:04 +0000 (UTC) Subject: Converting a .dbf file to a CSV file References: Message-ID: Johanna Pfalz wrote: > Is there a module/method in python to convert a file from .DBF > format to .CSV format? > > Johanna Pfalz > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715 There is an example provided. max From bearophileHUGS at lycos.com Wed Nov 22 21:14:58 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Nov 2006 18:14:58 -0800 Subject: changing list items In-Reply-To: <1164246882.289304.185580@e3g2000cwe.googlegroups.com> References: <1164246882.289304.185580@e3g2000cwe.googlegroups.com> Message-ID: <1164248098.763697.179680@j44g2000cwa.googlegroups.com> A possibile first solution: >>> alist = ['a','b','c','e','d','f'] >>> inf, sup = 2, 4 >>> alist[inf:sup] = ["t"] * (sup - inf) >>> alist ['a', 'b', 't', 't', 'd', 'f'] Bye, bearophile From cvanarsdall at mvista.com Wed Nov 8 13:21:36 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 08 Nov 2006 10:21:36 -0800 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: <1163010004.3371.23.camel@localhost.localdomain> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> <4551FA0F.4000202@hotmail.com> <1163001215.177739.238130@k70g2000cwa.googlegroups.com> <45521E09.8050108@mvista.com> <1163010004.3371.23.camel@localhost.localdomain> Message-ID: <45522030.9080808@mvista.com> Cliff Wells wrote: > On Wed, 2006-11-08 at 10:12 -0800, Carl J. Van Arsdall wrote: > >> BartlebyScrivener wrote: >> > > >>> I agree. And Python is an extremely serious matter calling for decorum >>> and propriety. >>> >>> >> Lol, is it really now? And I suppose its your definition of decorum and >> not mine right? Things like that are always relative. I think decorum >> would state that you should be an adult and not make a big deal out of >> nothing. But that's just me, and as I said, its all relative. >> > > I think you missed the irony in his statement (or perhaps confused > BartlebyScrivener with Beliavsky, who was the original plaintiff). > > Ah, yea, you are right. My apologies. -c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From Tim.Golden at viacom-outdoor.co.uk Tue Nov 28 06:00:47 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 28 Nov 2006 11:00:47 -0000 Subject: Accessing file metadata on windows XP In-Reply-To: <1164704134.100569.101270@j72g2000cwa.googlegroups.com> Message-ID: [wileyregister22 at gmail.com] | When rightclicking a, for example, pdf file on windows, one normally | gets a screen with three or four tags. Clicking on one of the summary | tag one can get some info like "title", "Author", "category", | "keyword" | etc.. This (Delphi) article is about the most informative I managed to dig up: http://tinyurl.com/rx9hc In short, you need to use the StgOpenStorageEx function which the (pywin32) pythoncom module exposes. There are quite a few caveats and you'll have to dig around for flag/constants etc. but it should be quite do-able. (Still don't have the time to try it myself, tho') Happy Hunting! TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Nov 9 16:29:39 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 09 Nov 2006 22:29:39 +0100 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> Message-ID: <4rhku3FriokeU2@mid.individual.net> Michael Hobbs wrote: > That is, assume that the expression ends at the colon, not at the > newline. That would make this type of statement possible: > if color == red or > color == blue or > color == green: > return 'primary' > Right now, such a statement would have to be spelled thus: > if color == red or \ > color == blue or \ > color == green: > return 'primary' > or > if (color == red or > color == blue or > color == green): > return 'primary' What about if color == red or blue or green: return 'primary' :) Really, I think it'd be more mess to let the if statement's end only depend on ":". I think there could arise situations that are messy to debug. If I need multiple lines I prefer the parentheses. Regards, Bj?rn -- BOFH excuse #295: The Token fell out of the ring. Call us when you find it. From george.sakkis at gmail.com Wed Nov 1 01:11:04 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 31 Oct 2006 22:11:04 -0800 Subject: High level csv reader Message-ID: <1162361464.706313.221590@e64g2000cwd.googlegroups.com> It occured to me that most times I read a csv file, I'm often doing from scratch things like assigning labels to columns, mapping fields to the appropriate type, ignoring some fields, changing their order, etc. Before I go on and reinvent the wheel, is there a generic high level wrapper around csv.reader that does all this ? Thanks, George From filipwasilewski at gmail.com Sun Nov 19 15:28:56 2006 From: filipwasilewski at gmail.com (Filip Wasilewski) Date: 19 Nov 2006 12:28:56 -0800 Subject: About alternatives to Matlab References: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> <1163711343.870829.110030@h48g2000cwc.googlegroups.com> <1163791069.178490.198740@j44g2000cwa.googlegroups.com> <1163876220.121691.166740@h54g2000cwb.googlegroups.com> <1163879127.582231.268420@b28g2000cwb.googlegroups.com> Message-ID: <1163968136.877566.51130@m7g2000cwm.googlegroups.com> sturlamolden wrote: [...] > Here is the correct explanation: > > The factorization of the polyphase matrix is not unique. There are > several valid factorizations. Our implementations corresponds to > different factorizations of the analysis and synthesis poyphase > matrices, and both are in a sence correct, although numerically > different. Please correct me if I'm missing something but I'm pretty sure that choice of polyphase matrix factorization for given wavelet filter bank has influence only on speed and numerical stability of computation and not on the result itself. Particularly it should be possible to reconstruct analysis and synthesis filters from polyphase matrices regardless of the chosen factorization and both the discrete wavelet transform and the wavelet lifting scheme should give corresponding results for chosen wavelet (one can be rewritten in the form of other). cheers, fw From phil at riverbankcomputing.co.uk Sun Nov 5 17:16:21 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sun, 5 Nov 2006 22:16:21 +0000 Subject: ANN: PyQt v4.1 Released In-Reply-To: <1162754374.637359.322990@m73g2000cwd.googlegroups.com> References: <1162749608.733730.321970@k70g2000cwa.googlegroups.com> <1162754374.637359.322990@m73g2000cwd.googlegroups.com> Message-ID: <200611052216.21213.phil@riverbankcomputing.co.uk> On Sunday 05 November 2006 7:19 pm, Tool69 wrote: > Thanks Phil, > Can you put some hints about how to build QScintilla2 on Windows please > ? You mean something other than the installation instructions? Phil From insyte at gmail.com Thu Nov 16 01:38:24 2006 From: insyte at gmail.com (insyte at gmail.com) Date: 15 Nov 2006 22:38:24 -0800 Subject: More puzzling behavior while subclassing datetime Message-ID: <1163659104.321150.322650@e3g2000cwe.googlegroups.com> With assistance from Gabriel and Frederik (and a few old threads in c.l.p.) I've been making headway on my specialized datetime class. Now I'm puzzled by behavior I didn't expect while attempting to use some of the alternate datetime constructors. Specifically, it appears if I call GeneralizedTime.now() it calls the __new__ method of my class but treats keyword arguments as if they were positional. My class: class GeneralizedTime(datetime): def __new__(cls, time=None, *args, **kwargs): print time, args, kwargs if isinstance(time, str): timeValues, tzOffset = cls.stringToTimeTuple(time) return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset), **timeValues) elif isinstance(time, datetime): timeValues = time.timetuple()[:6] tzOffset = time.utcoffset() return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset), *timeValues) elif time is None: print "Still gotta figure out now to do this one..." else: raise Invalidtime(time) @staticmethod def stringToTimeTuple(timeString): ... regex that parses timeString ... >>> GeneralizedTime.today() 2006 (11, 16, 0, 35, 18, 747275, None) {} Traceback (most recent call last): File "", line 1, in ? File "gentime.py", line 106, in __new__ raise InvalidTime(time) gentime.InvalidTime: 2006 So it appears the time tuple is being passed to GeneralizedTime.__new__, but the first value is being assigned to the "time" argument. Is this a side effect of how datetime is implemented? Or am I doing something screwy? Thanks! -Ben From johnjsal at NOSPAMgmail.com Wed Nov 8 10:54:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 08 Nov 2006 10:54:24 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 7) In-Reply-To: References: <4550f7b9$0$14445$c3e8da3@news.astraweb.com> Message-ID: <4551fda4$0$7047$c3e8da3@news.astraweb.com> Chris Lambacher wrote: > On Tue, Nov 07, 2006 at 04:15:39PM -0500, John Salerno wrote: >> Cameron Laird wrote: >> >>> Fredrik Lundh collects pyidioms: >>> http://effbot.org/zone/python-lists.htm >> Not working? > perhaps http://effbot.org/zone/python-list.htm ? > Thanks guys! From duncan.booth at invalid.invalid Wed Nov 22 14:02:48 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Nov 2006 19:02:48 GMT Subject: utf - string translation References: Message-ID: hg wrote: >> or in other words, put this at the top of your file (where "utf-8" is >> whatever your editor/system is using): >> >> # -*- coding: utf-8 -*- >> >> and use >> >> u'' >> >> for all non-ASCII literals. >> >> >> > > Hi, > > The problem is that: > > # -*- coding: utf-8 -*- > import string > print len('a') > print len('?') > > returns 1 then 2 And if you do what was suggested and write: # -*- coding: utf-8 -*- import string print len(u'a') print len(u'?') then you get: 1 1 From titogarcia_nospamplease_ at gmail.com Mon Nov 6 10:04:03 2006 From: titogarcia_nospamplease_ at gmail.com (=?ISO-8859-1?Q?Ernesto_Garc=EDa_Garc=EDa?=) Date: Mon, 06 Nov 2006 16:04:03 +0100 Subject: Is there a commas-in-between idiom? In-Reply-To: References: Message-ID: > I've collected a bunch of list pydioms and other notes here: > > http://effbot.org/zone/python-list.htm Thank you for the suggestion. Ernesto From deets at nospam.web.de Mon Nov 27 17:54:58 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 27 Nov 2006 23:54:58 +0100 Subject: Can you fix up wrapper function argument signatures? In-Reply-To: References: Message-ID: <4t18m2F11nkd5U1@mid.uni-berlin.de> Gerard Brunick schrieb: > Consider: > > >>> def negate(func): > ... def wrapper(*args, **kwargs): > ... return not func(*args, **kwargs) > ... return wrapper > ... > >>> def f(x): > ... return x > 10 > ... > >>> g = negate(f) > >>> g(20) > False > >>> g(5) > True > > Now g has the argument signature of (*args, **kwargs). Pop-up help in > Python > Scripter(which is great by the way) tells me this, as does > > >>> g.func_code.co_varnames > ('args', 'kwargs') > > Is there anyway to fix this in negate? I assume that I can't just start > changing things in g.func_code since the bytecodes depend on the order > of variables and lots of other stuff that I don't claim to understand. > > Please note: From the new functools module, I see that one can set/update > __module__, __name__, __doc__, and __dict__ using the corresponding > attributes > from the wrapped function; however, none these fix up the argument > signature > do they? (I'm still running 2.4, so I haven't tried it.) You can use Michele Simionato's decorator-module. http://www.phyast.pitt.edu/~micheles/python/documentation.html HTH, Diez From lowz06 at gmail.com Sun Nov 19 02:24:08 2006 From: lowz06 at gmail.com (John (Z R) L) Date: 18 Nov 2006 23:24:08 -0800 Subject: How do I stop Python IDLE (GUI) from immediately exiting when I enter it? Message-ID: <1163921048.878108.145810@j44g2000cwa.googlegroups.com> Hi all, I am very new to programming, and I chose to study the Python language before C++. I am currently using the Wikibooks "Non-Programmer's Tutorial for Python", and am up to the section "Who goes there"? http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python/Who_Goes_There%3F But after clicking "run module" for " a = 1 print a a = a + 1 print a a = a * 2 print a " The results "1, 2, 4" didn't appear on the GUI screen, in fact nothing did. And I clicked twice again, this time, it exited the Python GUI program. I tried to enter back in, but it would quickly display "1 2 4" before exiting immediately within half a second. How do I stop the this exiting from occurring. Another problem I have is firewall. On my old computer (Windows 98) when using Python GUI, it can't run modules because of some firewall. But I thought firewalls were for internet sites only?! How do I fix this?? Thank you in advance, and I apologize for my ignorance. From sjmachin at lexicon.net Tue Nov 21 01:55:07 2006 From: sjmachin at lexicon.net (John Machin) Date: 20 Nov 2006 22:55:07 -0800 Subject: move up a level References: <1164089267.967125.190860@m73g2000cwd.googlegroups.com> Message-ID: <1164092107.601786.98390@f16g2000cwb.googlegroups.com> rplobue at yahoo.com wrote: > alright, noob question: i want to open a file in a directory above the > current one i'm in. I'm trying to use myfile = > open('../thefileiwant.txt', 'r') but the ../ doesn't work. How do i > do it? "Doesn't work" means what? Have you looked at the getcwd and chdir functions in the os module? You may wish to check that os.getcwd()'s notion of "current directory" is the same as yours. If you can't make any progress, ask again; do copy and paste the relevant parts of your script instead of trying to describe what you did. Also copy and paste output. Hint: use temporary print statements to show what is happening. HTH, John From samgurung at gmail.com Tue Nov 28 03:44:20 2006 From: samgurung at gmail.com (linuxfreak) Date: 28 Nov 2006 00:44:20 -0800 Subject: Libgmail Message-ID: <1164703460.303062.58620@80g2000cwy.googlegroups.com> hi guys, just starting out on python and libgmail... any documentation for libgmail outthere... basically what i want to do is develop an application to use gmail like and ftp server... should be able to upload files and download them as well.... thanks From martin at v.loewis.de Fri Nov 17 01:02:37 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 17 Nov 2006 07:02:37 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: <18c54$455d019b$59ad1aca$24364@news.flashnewsgroups.com> References: <18c54$455d019b$59ad1aca$24364@news.flashnewsgroups.com> Message-ID: <455d507d$0$18480$9b622d9e@news.freenet.de> gabor schrieb: > i also recommend this approach. > > also, raising an exception goes well with the principle of the least > surprise imho. Are you saying you wouldn't have been surprised if that had been the behavior? How would you deal with that exception in your code? Regards, Martin From michael at stroeder.com Wed Nov 15 12:41:59 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 15 Nov 2006 18:41:59 +0100 Subject: ANN: python-ldap-2.2.1 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.2.1 2006-11-15 Changes since 2.2.0: Modules/ * Fix for Python 2.5 free(): invalid pointer (see SF#1575329) * passwd() accepts None for arguments user, oldpw, newpw (see SF#1440151) Lib/ * ldif.LDIFWriter.unparse() now accepts instances of derived dict and list classes (see SF#1489898) From mailpitches at email.com Tue Nov 7 14:34:32 2006 From: mailpitches at email.com (mp) Date: 7 Nov 2006 11:34:32 -0800 Subject: Character encoding Message-ID: <1162928072.047884.163420@i42g2000cwa.googlegroups.com> I have html document titles with characters like >,  , and ‡. How do I decode a string with these values in Python? Thanks From metaperl at gmail.com Mon Nov 6 16:20:39 2006 From: metaperl at gmail.com (metaperl) Date: 6 Nov 2006 13:20:39 -0800 Subject: os x make install dies when compiling zipfile.py on 2.5 and 2.4.4 Message-ID: <1162848039.627681.22980@m7g2000cwm.googlegroups.com> I've tried both Python 2.4.4 and Python 2.5. I'm trying to build from source and install under a local directory Swarm since OpenSwarm requires builds of Postgres and Python under it's control. Ok, so I did ./configure --prefix=/Users/tbrannon/Documents/Python/Swarm/Python-2.5 but during make install I get this: Compiling /Users/tbrannon/Documents/Python/Swarm/Python-2.5/lib/python2.5/xmlrpclib.py ... Compiling /Users/tbrannon/Documents/Python/Swarm/Python-2.5/lib/python2.5/zipfile.py ... make: *** [libinstall] Error 1 and the same thing happens for Python 2.4.4 leaving me without a platform-depedent install directory in my build.. any ideas? From apardon at forel.vub.ac.be Thu Nov 9 05:36:07 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Nov 2006 10:36:07 GMT Subject: assigning values in __init__ References: <454faf57$0$12993$c3e8da3@news.astraweb.com> <4550daa6$0$26446$c3e8da3@news.astraweb.com> <4551fe01$0$7047$c3e8da3@news.astraweb.com> Message-ID: On 2006-11-09, Steven D'Aprano wrote: > On Thu, 09 Nov 2006 12:27:12 +1100, Ben Finney wrote: > >> John Salerno writes: >> >>> Ben Finney wrote: >>> > If you pass a *mapping* of the >>> > "I-might-want-to-add-more-in-the-future" values, then you get both >>> > explicit *and* expandable, without an arbitrary unneeded sequence. >>> >>> Do you mean by using the **kwargs parameter? >> >> No. > > Well, that'll teach me to put words in your mouth. > > [snip] >> If you have a group of named, semantically-related, unsequenced values, >> pass them into the function as a mapping object (a dict object). > > Still, if you are doing this: > > mapping_object = {"strength": roll_dice(10), > "intelligence":roll_dice(10), > "dexterity":roll_dice(10)} > my_character = Character(mapping_object) > > then there is little benefit to building the dict just for the purposes of > passing it to Character(), never to use it again, not when you can do this: > > my_character = Character(strength: roll_dice(10), > intelligence:roll_dice(10), dexterity:roll_dice(10)) But you will have to adapt this if you want extra or different characteristics. Personnally I would prefer something like: chardict = {} for char in characteristics: chardict[char] = roll_dice(10) my_character = Character(chardict) This way you only have to keep your characteristics in one place. > If you happen to already have collected your character attributes in a > mapping object for some other reason, then well and good, pass it into the > function. Otherwise, well, I believe the correct container for > character attributes is a Character, not a dict. What is wrong with keeping the character attributes in a dict in the Character? -- Antoon Pardon From tim at tdw.net Fri Nov 10 20:35:21 2006 From: tim at tdw.net (Tim Williams) Date: Sat, 11 Nov 2006 01:35:21 +0000 Subject: string to list of numbers conversion In-Reply-To: References: Message-ID: <9afea2ac0611101735p3d86780x58d1d90813ea68f4@mail.gmail.com> On 5 Nov 2006 04:34:32 -0800, jm.suresh at no.spam.gmail.com wrote: > Hi, > I have a string '((1,2), (3,4))' and I want to convert this into a > python tuple of numbers. But I do not want to use eval() because I do > not want to execute any code in that string and limit it to list of > numbers. > Is there any alternative way? > ?? I want to convert this into a python tuple of numbers ?? Do you want a python tuple with those numbers ie (1,2, 3,4), or a direct evaluation giving a tuple of tuples with those numbers, ie ((1,2), (3,4)) If the former then: >>> a, l = '((1,2), (3,4), (-5,-6),(12,-13), (a,b), (0.1,0.2))', [] >>> for c in a.split(','): ... try: ... c = c.replace('(','').replace(')','') ... if '.' in c: l.append(float(c)) ... else: l.append(int(c)) ... except: pass ... >>> tuple(l) (1, 2, 3, 4, -5, -6, 12, -13, 0.10000000000000001, 0.20000000000000001) >>> Its not so good with floats, but if you are only expecting integers you can use. >>> a, l = '((1,2), (3,4), (-5,-6),(12,-13), (a,b), (0.1,0.2))', [] >>> for c in a.split(','): ... try: l.append(int(c.replace('(','').replace(')',''))) ... except: pass ... >>> tuple(l) (1, 2, 3, 4, -5, -6, 12, -13) >>> HTH :) From danielkleinad at gmail.com Wed Nov 29 11:37:23 2006 From: danielkleinad at gmail.com (Daniel Klein) Date: Wed, 29 Nov 2006 16:37:23 GMT Subject: How to detect what type a variable is? References: <1164814586.113454.144090@l12g2000cwl.googlegroups.com> <12mragv4f1jhfb4@corp.supernews.com> <1164817535.636391.294310@n67g2000cwd.googlegroups.com> Message-ID: On 29 Nov 2006 08:25:35 -0800, "Leandro Ardissone" wrote: >great, thanks > >And how I can compare this "" output ? >I want to decide what to do if the var is an string and what to do if >not.. > >Tried with: >if type(artistList) == "": > >and >if type(artistList) == "list": > >but nothing.. Try it this way... >>> artistList = [] >>> isinstance(artistList, list) True >>> if isinstance(artistList, list): print "I'm a list." I'm a list. >>> Daniel Klein From Roberto.Bonvallet at cern.ch Wed Nov 29 10:14:47 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Wed, 29 Nov 2006 15:14:47 +0000 (UTC) Subject: Calling functions with dynamic arguments References: <1164812985.794957.26530@l12g2000cwl.googlegroups.com> Message-ID: SeanDavis12 wrote: > I have a dictionary like: > > {"a":1, "b":2} > > and I want to call a function: > > def func1(a=3,b=4): > print a,b > > so that I get a=1,b=2, how can I go about that? func1(**yourdict) -- Roberto Bonvallet From rrr at ronadam.com Sat Nov 11 02:13:03 2006 From: rrr at ronadam.com (Ron Adam) Date: Sat, 11 Nov 2006 01:13:03 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <4rhku3FriokeU2@mid.individual.net> <4rjlkqFrlskqU1@mid.individual.net> <4rk5giFrerjfU1@mid.individual.net> Message-ID: Steven D'Aprano wrote: > On Fri, 10 Nov 2006 21:24:50 +0100, Bjoern Schliessmann wrote: > >> Marc 'BlackJack' Rintsch wrote: >> >>> No it doesn't -- look again at the example given above. It's >>> legal syntax in Python but doesn't have the semantics implied by >>> the example. >> Sorry, I don't understand -- what is the difference between the >> example as it is and the implied semantics of it? > > Inform 6 "x == blue or red or yellow" is equivalent to the Python > > x == blue or x == red or x == yellow Maybe it should have been expressed as: x == (blue or red or yellow) Cheers, Ron From joseph.sheedy at gmail.com Mon Nov 13 14:29:21 2006 From: joseph.sheedy at gmail.com (velotron) Date: 13 Nov 2006 11:29:21 -0800 Subject: Python memory usage In-Reply-To: <1163104700.515953.4210@b28g2000cwb.googlegroups.com> References: <1162964551.328495.211090@f16g2000cwb.googlegroups.com> <1162966901.337252.45720@m7g2000cwm.googlegroups.com> <1162967080.689144.320940@f16g2000cwb.googlegroups.com> <1163104700.515953.4210@b28g2000cwb.googlegroups.com> Message-ID: <1163446161.594913.269050@b28g2000cwb.googlegroups.com> (hello group) On Nov 9, 8:38 pm, "Klaas" wrote: > I was referring specifically to abominations like range(1000000) However, there are plenty of valid reasons to allocate huge lists of integers. This issue has been worked on: http://evanjones.ca/python-memory.html http://evanjones.ca/python-memory-part3.html My understanding is that the patch allows most objects to be released back to the OS, but can't help the problem for integers. I could be mistaken. But on a clean Python 2.5: x=range(10000000) x=None The problem exists for floats too, so for a less contrived example: x=[random.weibullvariate(7.0,2.0) for i in xrange(10000000)] x=None Both leave the Python process bloated in my environment. Is this problem a good candidate for the FAQ? --Joseph From jkn_gg at nicorp.f9.co.uk Mon Nov 20 10:38:15 2006 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 20 Nov 2006 07:38:15 -0800 Subject: Misleading IOerror when opening a non-existent file for append? Message-ID: <1164037095.148334.157670@e3g2000cwe.googlegroups.com> Hi all Python 2.4.2 (#1, Apr 26 2006, 23:35:31) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ifile=open("\\no_such_dir\\no_such_file" ,'a') Traceback (most recent call last): File "", line 1, in ? IOError: invalid mode: a >>> but: >>> ifile=open("\\no_such_dir\\no_such_file" ,'r') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: '\\no_such_dir\\no_such_file' >>> This 'invalid mode: a' error message seems weird to me. Is this a bug or am I missimg something? Thanks Jon N From dlenski at gmail.com Mon Nov 13 13:05:04 2006 From: dlenski at gmail.com (Dan Lenski) Date: 13 Nov 2006 10:05:04 -0800 Subject: Singleton Class Exception In-Reply-To: <1163437486.036537.270190@h54g2000cwb.googlegroups.com> References: <1163437486.036537.270190@h54g2000cwb.googlegroups.com> Message-ID: <1163441104.781863.57590@i42g2000cwa.googlegroups.com> dischdennis wrote: > the line "raise Singleton.__single" invokes in my class the following > error: > > exceptions must be classes, instances, or strings (deprecated), not > PurchaseRequisitionController Denis, Jason's explanation is correct! You are trying to use the Singleton instance as the exception, which is not only confusing but illegal. The argument of raise should be an instance of a class derived from Exception. You should define some kind of informative Exception class, e.g.: class SingletonException(Exception): pass class Singleton: __single = None def __init__( self ): if Singleton.__single: raise SingletonException() Singleton.__single = self foo = Singleton() # works bar = Singleton() # raises SingletonException Dan From fredrik at pythonware.com Sun Nov 26 06:22:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 26 Nov 2006 12:22:43 +0100 Subject: who is maintainer of xml-rpc module? In-Reply-To: References: Message-ID: Mark Harrison wrote: > So, I've made a couple of small but useful additions to > the xml-rpc package. Is there an assigned maintainer > of the package I should communicate with? post your patch here: http://sourceforge.net/tracker/?group_id=5470&atid=305470 From setchell.dave at gmail.com Mon Nov 6 00:03:26 2006 From: setchell.dave at gmail.com (Dave Setchell) Date: Sun, 05 Nov 2006 23:03:26 -0600 Subject: Awesome Python Information References: <1162753631.297470.315570@m7g2000cwm.googlegroups.com> Message-ID: <9IKdnVDSOP6DX9PYnZ2dnUVZ_sqdnZ2d@comcast.com> On Sun, 05 Nov 2006 17:05:10 -0500, jim-on-linux wrote: > Thanks for the heads up. I spend enough time with > the email without having to chase gosts. > > jim-on-linux > http://www.inqvista.com > > > > > > > On Sunday 05 November 2006 16:39, Paul McGuire > wrote: >> "Brandon" wrote in message >> news:1162753631.297470.315570 at m7g2000cwm.google >>groups.com... >> >> > Check out: www.ChezBrandon.com >> >> By which he means, "do NOT waste your time >> checking out this ridiculous website with >> absolutely no Python whatever anywhere." (This >> is the idiot who claims he saved the Congress >> from some Mossad poison gas attack, or >> whatever.) >> >> -- Paul So I'm using a new fangled newsreader...[pan] and thought i'd test it's posting and headers on this silly thread...sorry if I wasted anyones time!. From bj_666 at gmx.net Sat Nov 4 08:55:27 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 04 Nov 2006 14:55:27 +0100 Subject: py2exe questions References: <454BB574.9030607@websafe.com> <1162646535.744282.95290@m7g2000cwm.googlegroups.com> Message-ID: In <1162646535.744282.95290 at m7g2000cwm.googlegroups.com>, Jerry wrote: > Despite what everyone is saying though, I believe that any and all > solutions will require that the byte-code be extracted to some > directory before being run. It's not Python bytecode. The problem is native libraries which are hard to run from memory without a real file backing it on some platforms. A pure Python program/package should be possible without temporary files. Ciao, Marc 'BlackJack' Rintsch From anthra.norell at vtxmail.ch Thu Nov 2 09:37:18 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Thu, 02 Nov 2006 15:37:18 +0100 Subject: unescape HTML entities In-Reply-To: References: <45449EAC.4070103@vtxmail.ch> Message-ID: <454A029E.8060603@vtxmail.ch> Rares Vernica wrote: > Hi, > > I downloades 2.2 beta, just to be sure I have the same version as you > specify. (The file names are no longer funny.) Anyway, it does not seem > to do as you said: > > In [14]: import SE > > In [15]: SE.version > -------> SE.version() > Out[15]: 'SE 2.2 beta - SEL 2.2 beta' > > In [16]: HTM_Decoder = SE.SE ('HTM2ISO.se') > > In [17]: test_string = ''' > ....: ø=(xf8) # 248 f8 > ....: ù=(xf9) # 249 f9 > ....: ú=(xfa) # 250 fa > ....: û=(xfb) # 251 fb > ....: ü=(xfc) # 252 fc > ....: ý=(xfd) # 253 fd > ....: þ=(xfe) # 254 fe > ....: é=(xe9) > ....: ê=(xea) > ....: ë=(xeb) > ....: ì=(xec) > ....: í=(xed) > ....: î=(xee) > ....: ï=(xef) > ....: ''' > > In [18]: print HTM_Decoder (test_string) > > ø=(xf8) # 248 f8 > ù=(xf9) # 249 f9 > ú=(xfa) # 250 fa > û=(xfb) # 251 fb > ü=(xfc) # 252 fc > ý=(xfd) # 253 fd > þ=(xfe) # 254 fe > é=(xe9) > ê=(xea) > ë=(xeb) > ì=(xec) > í=(xed) > î=(xee) > ï=(xef) > > > In [19]: > > Thanks, > Ray > > > > Frederic Rentsch wrote: > >> Rares Vernica wrote: >> >>> Hi, >>> >>> How can I unescape HTML entities like " "? >>> >>> I know about xml.sax.saxutils.unescape() but it only deals with "&", >>> "<", and ">". >>> >>> Also, I know about htmlentitydefs.entitydefs, but not only this >>> dictionary is the opposite of what I need, it does not have " ". >>> >>> It has to be in python 2.4. >>> >>> Thanks a lot, >>> Ray >>> >>> >> One way is this: >> >> >>> import SE # >> Download from http://cheeseshop.python.org/pypi/SE/2.2%20beta >> >>> SE.SE ('HTM2ISO.se')('input_file_name', 'output_file_name') # >> HTM2ISO.se is included >> 'output_file_name' >> >> For repeated translations the SE object would be assigned to a variable: >> >> >>> HTM_Decoder = SE.SE ('HTM2ISO.se') >> >> SE objects take and return strings as well as file names which is useful >> for translating string variables, doing line-by-line translations and >> for interactive development or verification. A simple way to check a >> substitution set is to use its definitions as test data. The following >> is a section of the definition file HTM2ISO.se: >> >> test_string = ''' >> ø=(xf8) # 248 f8 >> ù=(xf9) # 249 f9 >> ú=(xfa) # 250 fa >> û=(xfb) # 251 fb >> ü=(xfc) # 252 fc >> ý=(xfd) # 253 fd >> þ=(xfe) # 254 fe >> é=(xe9) >> ê=(xea) >> ë=(xeb) >> ì=(xec) >> í=(xed) >> î=(xee) >> ï=(xef) >> ''' >> >> >>> print HTM_Decoder (test_string) >> >> ?=(xf8) # 248 f8 >> ?=(xf9) # 249 f9 >> ?=(xfa) # 250 fa >> ?=(xfb) # 251 fb >> ?=(xfc) # 252 fc >> ?=(xfd) # 253 fd >> ?=(xfe) # 254 fe >> ?=(xe9) >> ?=(xea) >> ?=(xeb) >> ?=(xec) >> ?=(xed) >> ?=(xee) >> ?=(xef) >> >> Another feature of SE is modularity. >> >> >>> strip_tags = ''' >> ~<(.|\x0a)*?>~=(9) # one tag to one tab >> ~~=(9) # one comment to one tab >> | # run >> "~\x0a[ \x09\x0d\x0a]*~=(x0a)" # delete empty lines >> ~\t+~=(32) # one or more tabs to one space >> ~\x20\t+~=(32) # one space and one or more tabs to >> one space >> ~\t+\x20~=(32) # one or more tab and one space to >> one space >> ''' >> >> >>> HTM_Stripper_Decoder = SE.SE (strip_tags + ' HTM2ISO.se ') # >> Order doesn't matter >> >> If you write 'strip_tags' to a file, say 'STRIP_TAGS.se' you'd name it >> together with HTM2ISO.se: >> >> >>> HTM_Stripper_Decoder = SE.SE ('STRIP_TAGS.se HTM2ISO.se') # >> Order doesn't matter >> >> Or, if you have two SE objects, one for stripping tags and one for >> decoding the ampersands, you can nest them like this: >> >> >>> test_string = "

> style='line-height:110%'>René est un garçon qui >> paraît plus âgé.

" >> >> >>> print Tag_Stripper (HTM_Decoder (test_string)) >> Ren? est un gar?on qui para?t plus ?g?. >> >> Nesting works with file names too, because file names are returned: >> >> >>> Tag_Stripper (HTM_Decoder ('input_file_name'), 'output_file_name') >> 'output_file_name' >> >> >> Frederic >> >> >> >> > > Ray, I am sorry you're having a problem. I cannot duplicate it. It works fine here. I suspect that SE.SE doesn't find your file HTM2ISO.SE. Do this: >>> HTM_Decoder = SE.SE ('HTM2ISO.SE') >>> HTM_Decoder.show_log () Thu Nov 02 15:15:39 2006 - Compiler - Ignoring single word 'HTM2ISO.SE'. Not an existing file 'HTM2ISO.SE'. If you see this, then you might have forgotten to include the path with the file name. Rather than getting an old version, you could just have renamed the to py-files. Version 2.3 has some minor bugs corrected. I fixed the names and tried to re-upload to the Cheese Shop and the damn thing stubbornly refuses the upload after having required that I delete the file I was going to replacing. So it isn't there anymore and the replacement isn't there yet. I'll be working on this. In the meantime I'll be happy to direct-mail V2.3 by request. Frederic From pavlovevidence at gmail.com Mon Nov 13 06:38:29 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 13 Nov 2006 03:38:29 -0800 Subject: Python 3000 idea -- + on iterables -> itertools.chain References: <1163385266.824914.265490@b28g2000cwb.googlegroups.com> <1163408380.747399.18750@h54g2000cwb.googlegroups.com> Message-ID: <1163417909.768399.199650@h54g2000cwb.googlegroups.com> George Sakkis wrote: > Fredrik Lundh wrote: > > > George Sakkis wrote: > > > > > The base object class would be one candidate, similarly to the way > > > __nonzero__ is defined to use __len__, or __contains__ to use __iter__. > > > > > > Alternatively, iter() could be a wrapper type (or perhaps mixin) > > > instead of a function, something like: > > > > so you're proposing to either make *all* objects respond to "+", or > > introduce limited *iterator* algebra. > > If by 'respond to "+"' is implied that you can get a "TypeError: > iterable argument required", as you get now for attempting "x in y" for > non-iterable y, why not ? Bad idea on many, many levels. Don't go there. > Although I like the iterator algebra idea > better. > > > not sure how that matches the OP's wish for "mostly backwards > > compatible" support for *iterable* algebra, really... > > Given the subject of the thread, backwards compatibility is not the > main prerequisite. Besides, it's an *extension* idea; allow operations > that were not allowed before, not the other way around or modifying > existing semantics. You missed the important word (in spite of Fredrick's emphasis): iterable. Your iter class solution only works for *iterators* (and not even all iterators); the OP wanted it to work for any *iterable*. "Iterator" and "iterable" are protocols. The only way to implement what the OP wanted is to change iterable protocol, which means changing the documentation to say that iterable objects must implement __add__ and that it must chain the iterables, and updating all iterable types to do this. Besides the large amount of work that this will need, there are other problems. 1. It increases the burden on third party iterable developers. Protocols should be kept as simple as possible for this reason. 2. Many iterable types already implement __add__ (list, tuple, string), so this new requirement would complicate these guys a lot. > Of course, programs that attempt forbidden > expressions on purpose so that they can catch and handle the exception > would break when suddenly no exception is raised, but I doubt there are > many of those... 3. While not breaking backwards compatibility in the strictest sense, the adverse effect on incorrect code shouldn't be brushed aside. It would be a bad thing if this incorrect code: a = ["hello"] b = "world" a+b suddenly started failing silently instead of raising an exception. Carl Banks From ytlim1 at gmail.com Fri Nov 17 07:15:33 2006 From: ytlim1 at gmail.com (Why Tea) Date: 17 Nov 2006 04:15:33 -0800 Subject: What python modules are available? Message-ID: <1163765733.745577.116670@m73g2000cwd.googlegroups.com> How do I find out what python modules are installed on a Solaris platform? I tried to import numarray, but python couldn't find it. /Why Tea From shane at hathawaymix.org Fri Nov 24 04:10:29 2006 From: shane at hathawaymix.org (Shane Hathaway) Date: Fri, 24 Nov 2006 02:10:29 -0700 Subject: The Python Papers Edition One In-Reply-To: <1164340388.885058.264750@l12g2000cwl.googlegroups.com> References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <7xodqyn5kd.fsf@ruckus.brouhaha.com> <1164323350.988946.209350@l12g2000cwl.googlegroups.com> <1164340388.885058.264750@l12g2000cwl.googlegroups.com> Message-ID: <4566B705.20102@hathawaymix.org> tleeuwenburg at gmail.com wrote: > Ben Finney wrote: >> "tleeuwenburg at gmail.com" writes: >> >>> Yes, it's true that you can't resell copies of The Python Papers for >>> personal profits, but you may derive from it, reproduce and >>> propagate it. You're quite right to point it out. >> Then please revise the false statement that the publication is "free >> as in beer and freedom", or make it true by releasing the documents >> under a license that does grant conventional free-software freedoms. >> >> -- >> \ "They can not take away our self respect if we do not give it | >> `\ to them." -- Mahatma Gandhi | >> _o__) | >> Ben Finney > > I thought I just had. In what way does the statement "Yes, it's true > that you can't resell copies of The Python Papers for personal profits, > but you may derive from it, reproduce and propagate it" not provide > such a revision and clarification? Seriously, let me know what exact > statement you feel needs to be made, and I will endorse it accordingly > if it is accurate. The phrase "free as in freedom" is commonly understood differently from the way you are using it. Free as in freedom usually grants the right to distribute for a fee. Many Linux distributors depend on that right; otherwise they wouldn't have the right to sell CDs. IMHO your licensing terms are fine; you don't need to switch from the CC license. Just avoid the term "free as in freedom", since the Free Software Foundation has assigned that phrase a very specific meaning. Shane From Jeff.Demel at JavelinDirect.com Thu Nov 16 13:42:07 2006 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Thu, 16 Nov 2006 12:42:07 -0600 Subject: Python v PHP: fair comparison? Message-ID: <136ED738BD4F1545B97E4AC06FF6370734BFDD@DMSP-MSG-EVS01.mail.pvt> > Walterbyrd wrote: >> Okay, where can I get Python and Apache 2.X for $10 a year? > I replied: > Webfaction.com Tkc then came back with: >Um, I think you're off by an order of magnitude. Walterbyrd asked > about $10/*year* and webfaction.com charges $7.50/*month*. >Well, I suppose if one only needed one and a third months of >hosting during the course of the year, it might do for ya. ;-) Yup, I read month, not year. My bad. What kind of hosting does one get for $10 a *year*? And I'm not just talking Python here, but any hosting at all. That seems like an absurd price requirement to me. I was stoked to find Python/Apache2.0/Django/IMAP Email/2GB storage for about 10 or so bucks a *month*. -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From shejo284 at gmail.com Fri Nov 17 02:51:48 2006 From: shejo284 at gmail.com (Sheldon) Date: 16 Nov 2006 23:51:48 -0800 Subject: C extensions and memory leakage Message-ID: <1163749907.941949.201880@h48g2000cwc.googlegroups.com> Hi, I have a program that I have extended with a C function. When the program is run once or twice everything is ok but in a loop of 5 to 12 iterations, the memory runs out and the program crashes. Now I have gone through this program thoroughly to check if all arrays have been deallocated prior to exiting and they have, but still the problem exists. Now I am wondering if the problem is in Python and the wrapper? Does anybody have any idea or experience with this? I am running on Mandrake10 using python 2.3. I am not exactly sure which C wrapper I am using as I have copied it from another person. thanks in advance, /Sheldon From theller at ctypes.org Fri Nov 10 15:11:26 2006 From: theller at ctypes.org (Thomas Heller) Date: Fri, 10 Nov 2006 21:11:26 +0100 Subject: announce: FAQs suggested In-Reply-To: <1163168871.092708.83150@f16g2000cwb.googlegroups.com> References: <1163166123.773324.126160@m7g2000cwm.googlegroups.com> <1163167884.303515.257820@k70g2000cwa.googlegroups.com> <1163168871.092708.83150@f16g2000cwb.googlegroups.com> Message-ID: <4554DCEE.5080301@ctypes.org> p.lavarre at ieee.org schrieb: >> > > > http://effbot.org/pyfaq/suggest.htm >> > > FAQ: How do I say returns void in ctypes? >> > That's in the ctypes documentation, where it belongs. >> >> Thank you, before I never had found "Use None for void a function not >> returning anything" at: >> http://starship.python.net/crew/theller/ctypes/reference.html This sentence: Use None for void a function not returning anything of course makes no sense. What I had in mind was: Use None for a void function not returning anything but that can certainly improved. Suggestions? Thomas From mike.klaas at gmail.com Mon Nov 20 17:28:23 2006 From: mike.klaas at gmail.com (Klaas) Date: 20 Nov 2006 14:28:23 -0800 Subject: IronPython Community Edition r4 In-Reply-To: References: Message-ID: <1164061703.755033.306570@k70g2000cwa.googlegroups.com> Sanghyeon Seo wrote: > _sre.py from PyPy, a pure Python implementation of Python's regular > expression, is included and enabled by default, overriding > IronPython's implementation based on System.Text.RegularExpression. > You can comment out "install_sre_py()" line from site.py to disable > this. Interesting--how does this fare, performance-wise? -Mike From no-spam at no-spam-no-spam.invalid Fri Nov 3 12:13:51 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 03 Nov 2006 18:13:51 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> Message-ID: Daniel Dittmar wrote: > robert wrote: >> ---- Question Besides: do concurrent INC/DEC machine OP-commands >> execute atomically on Multi-Cores as they do in Single-Core threads? > > No on the level that that Python reference counting is implemented. The > CPUs have often special assembler ops for these operations. I think that > it's even more complicated as some machines require additional read and > write barriers around these operations. > >>> Take a look at IPython1 and it's parallel computing capabilities [1, > [...] >> I do selected things with interprocess shared memory techniques >> already. Thats medium efficent. >> Multiple interpreters inside one process seem to be most promising for >> seemless multi-core programming. > > Both IPython and Jython use multiple CPUs without the GIL, so you don't > need to add the complication of multiple interpreters. (IPython is only a special "python network terminal" as already said.) With Jython I'm not familiar. Yet I think going to Jython will first cost more performance than you can win - at least on only dual cores as we have now. In 5 years with > 8x MPU systems this may be different ... Does Jython really eliminate the GIL? What happens when different threads alter/read a dict concurrently - the basic operation in python, which is usually not protected by locks. Does Jython use a dict data type (and other collection types) which lock during _each_ access? in case - that may be very expensive. > > As all Python objects share the same > > malloc space - thats the key requirement in order to get the main > > effect. As soon as with have object pickling in between its well away > > from this very discussion. > > There's the complication that CPython has garbage collection in addition > to reference counting. I'm not sure what happens when the garbage > collector looks at objects rooted in another interpreter. garbage is collected earliest, when the refcount went to 0. If it ever went to 0, no one will ever use such object again. Thus GC should not be different at all. robert From sjmachin at lexicon.net Sun Nov 26 06:07:25 2006 From: sjmachin at lexicon.net (John Machin) Date: 26 Nov 2006 03:07:25 -0800 Subject: problem about list indexing In-Reply-To: References: <1164529513.862598.221550@h54g2000cwb.googlegroups.com> Message-ID: <1164539245.375487.300190@j44g2000cwa.googlegroups.com> Steven D'Aprano wrote: > On Sun, 26 Nov 2006 00:25:13 -0800, hollowspook wrote: > > > Hi, there > > > > a = range(100) > > > > if I want to use No 7, 11, 56,90 in a, then the only way I do is [a[7], > > a[11], a[56], a[90]]. > > Is there any other way? > > a = [7, 11, 56, 90] > > Are those numbers supposed to be in some sort of series? They aren't an > arithmetic series: > > (11 - 7) = 4 > (56 - 11) = 45 # not a constant difference > > nor are they a geometric series: > > (11/7) = 1.57 > (56/11) = 5.09 # not a constant ratio > > They don't look like some form of a Fibonacci series: > > 7+11 != 56 > 11+56 != 90 > > If they're just "random" numbers, plucked out of thin air, then you > probably can't calculate them and you'll need to just create them in a > list a = [7, 11, 56, 90]. > Actually, it's a cubic polynomial ;-) | >>> def f(x): | ... return ( | ... 7 | ... + 4 * x | ... + 41 * x * (x - 1) // 2 | ... - 52 * x * (x - 1) * (x - 2) // 6 | ... ) | ... | >>> [f(x) for x in range(4)] | [7, 11, 56, 90] HTH, John From samantha7395 at hotmail.com Thu Nov 16 18:48:09 2006 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 16 Nov 2006 15:48:09 -0800 Subject: Writing to Registry Message-ID: I am working with this recipes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66011 The problem I am having is setting a hex value. This line --- SetValueEx(aKey,"MyNewKey",0, REG_SZ, r"c:\winnt\explorer.exe") I want something Like -- SetValueEx(aKey,"MyNewSize",0, REG_SZ, 120 or some value) Help would be appreciated. S From sjmachin at lexicon.net Fri Nov 24 03:54:35 2006 From: sjmachin at lexicon.net (John Machin) Date: 24 Nov 2006 00:54:35 -0800 Subject: Local variables persist in functions? In-Reply-To: <1164355869.607182.278200@l12g2000cwl.googlegroups.com> References: <1164355869.607182.278200@l12g2000cwl.googlegroups.com> Message-ID: <1164358475.569240.115450@45g2000cws.googlegroups.com> 120psi at gmail.com wrote: > I'm a bit baffled. Here is a bit of fairly straightforward code: > > def _chunkify( l, chunkSize, _curList = list() ): Quite apart from the default argument problem, which Duncan has addressed, you have some problems with style and variable names. In particular: give variables meaningful names ; "L".lower() is not meaningful and also suffers from confusion with the digit 1 in some fonts. There is no necessity for the _ in _curList in the above line. Please consider reading http://www.python.org/dev/peps/pep-0008/ > print _curList # yay for printf debugging > if len( l ) <= chunkSize: > _curList.append( l ) > else: > newChunk = l[:chunkSize] > _curList.append( newChunk ) > _chunkify( l[chunkSize:], chunkSize, _curList ) > return _curList > > _chunkify simply breaks a sequence into a sequence of smaller lists of > size <= chunkSize. The first call works fine, but if I call it > multiple times, weirdness happens. > > chunks = _chunkify( list, size ) # _curList keeps its previous value! > chunks = _chunkify( list, size, list() ) # this works as expected Is the first "list" a list, or is it the name of the same function that you are calling to provide the 3rd argument? [snip] HTH, John From maxerickson at gmail.com Wed Nov 8 19:11:20 2006 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 9 Nov 2006 00:11:20 +0000 (UTC) Subject: PIL - Pixel Level Image Manipulation? References: <312cfe2b0611080853x5e388fbfpb04f2bdb811eafa6@mail.gmail.com> <312cfe2b0611081156v619bd82eu782b068bfd2cf558@mail.gmail.com> Message-ID: "Gregory Pi?ero" wrote: > On 11/8/06, Gregory Pi?ero wrote: >> I want to be able to randomly change pixels in an image and view >> the results. I can use whatever format of image makes this >> easiest, e.g., gray scale, bit tonal, etc. >> >> Ideally I'd like to keep the pixels in an intermediate format >> like a list of (integers?) or an array and convert that to an >> image as needed. >> >> I'm hoping someone has some experience on this and could offer >> some advice or code. I thought it would be easy in PIL but I'm >> not sure. > > I did find these functions after more searching: > http://mail.python.org/pipermail/image-sig/2002-July/001914.html > > Perhaps I'll try those out tonight if I don't hear of anything > better in the meantime. > > -Greg Maybe something of use at: http://online.effbot.org/2005_10_01_archive.htm#20051003 max From bdesth.quelquechose at free.quelquepart.fr Thu Nov 23 18:19:33 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 24 Nov 2006 00:19:33 +0100 Subject: Access to variable from external imported module In-Reply-To: <1164319761.451409.196660@j44g2000cwa.googlegroups.com> References: <1164316786.875306.276460@h54g2000cwb.googlegroups.com> <1164319761.451409.196660@j44g2000cwa.googlegroups.com> Message-ID: <4566275f$0$6178$426a74cc@news.free.fr> GinTon a ?crit : > Sorry, I mean access to local variable from a method One of the most surprising properties of local variables is that they are, well... local. From paul at boddie.org.uk Fri Nov 24 05:41:47 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 24 Nov 2006 02:41:47 -0800 Subject: The Python Papers Edition One References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <7xodqyn5kd.fsf@ruckus.brouhaha.com> <1164323350.988946.209350@l12g2000cwl.googlegroups.com> <1164340388.885058.264750@l12g2000cwl.googlegroups.com> Message-ID: <1164364907.554740.212140@j44g2000cwa.googlegroups.com> Shane Hathaway wrote: > > IMHO your licensing terms are fine; you don't need to switch from the CC > license. Just avoid the term "free as in freedom", since the Free > Software Foundation has assigned that phrase a very specific meaning. Agreed. It should also be noted that Debian - amongst the strictest with regard to software and content licensing - do not regard the CC licences as being "free as in freedom": http://en.wikipedia.org/wiki/Creative_Commons_licenses http://people.debian.org/~evan/ccsummary.html http://people.debian.org/~evan/draftresponse.txt Consequently, it may be appropriate to remind authors to also make their works more widely available under a licence that may permit further distribution, if that is desirable. Paul P.S. I still don't really understand why the FSF unreservedly recommends the Free Art licence when it has a "choice of law" clause that has prevented things like the GPL-compatibility of other licences in the past. From fredrik at pythonware.com Sun Nov 19 11:22:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Nov 2006 17:22:04 +0100 Subject: A little confuse In-Reply-To: <1163950602.32026.9.camel@Tiredbones.lan> References: <1163950602.32026.9.camel@Tiredbones.lan> Message-ID: infotechsys at pivot.net wrote: > When I run this code in the pdb it works. > accountNbr = 1 > for testLine in ftest.readlines(): > acct = testLine[1:2] #there account number > if accountNbr == int(acct): > accountNbr = accountNbr + 1 > > When I run without the debugger I get this error. > > File "./casco.py", line 62, in process > if accountNbr == int(acct): > ValueError: invalid literal for int(): " > > Can someone explain? adding a print repr(acct), repr(testLine) debug statement after the "acct = testLine" line might give you the clues you need to solve this. From grante at visi.com Fri Nov 17 10:41:21 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 17 Nov 2006 15:41:21 -0000 Subject: pyserial port connection problem References: <1163764748.744393.130660@m7g2000cwm.googlegroups.com> Message-ID: <12lrm118tk0sv69@corp.supernews.com> On 2006-11-17, Jon wrote: > I ran py2exe on the program (which uses wxpython for its gui) > and sent the output from the py2exe to another computer. now > when I try to run it on this other computer it fails to open > the port. it gives the error that it cannot createfile. the > code I'm using to connect is the same as it is when it worked > on my computer. Are you sure you're using the correct com port? > I do notice that pyserial sees this port on the other computer as > \\\\.\\COM14 - while windows device manager displays it as COM14. That's just another one of the many fun and wonderful little bits of brokenness in MS Windows. COM14 can't be opened using the name COM14. You have to call it \\.\COM14. Using the unadorned COMx name only works for COM1-COM9. Since the dimwits at MS decided to use C's "escape" character as a directory separator, you've got to double it up (e.g. "\\\\.\\COM14") to get the string you really want. > On the other computer the data is properly displayed in > Hyperterminal when opened on COM14. What it displays as on other computers is irrelevant. Just because a USB serial adapter shows up as COM14 on machine A, that doesn't mean it's going to be COM14 on machine B. > how can I resolve this issue? Go look in the device manager to see what com port you should be using. -- Grant Edwards grante Yow! There's a SALE on at STRETCH SOCKS down at the visi.com "7-11"!! From steve at REMOVE.THIS.cybersource.com.au Sat Nov 4 00:49:21 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 04 Nov 2006 16:49:21 +1100 Subject: Physical constants References: <73D46C5F-12AE-4700-86D2-7FAE0DEF6C54@mac.com> Message-ID: Apologies for breaking threading, but my ISP seems to have eaten the original post from Tommy. Hence I'm replying to a reply. Tommy Grav wrote: > I have some code for doing orbital computations. The code is kind of > extensive with many classes, each having several functions. In these > functions I need to use constants (like the gravitational constant). > What is the best way of implementing a solution when constants are > used in several different classes and functions? If all your code is in the one file, then it couldn't be simpler. E.g.: # orbital computations # define some constants G = 1.0 # gravity is strong in this universe... # define some functions def force_of_gravity(m1, m2, r): return G*m1*m2/r**2 -- Steven. From orsenthil at gmail.com Mon Nov 13 08:35:15 2006 From: orsenthil at gmail.com (Phoe6) Date: 13 Nov 2006 05:35:15 -0800 Subject: httplib.InvalidURL: nonnumeric port: For characters in theproxypassword in URL In-Reply-To: References: <1163408210.915911.327430@k70g2000cwa.googlegroups.com> <1163423258.919153.281260@b28g2000cwb.googlegroups.com> Message-ID: <1163424914.967174.302610@e3g2000cwe.googlegroups.com> Fredrik Lundh wrote: > "Phoe6" wrote: > > > - use urllib.quote() to covert the proxy url to a quoted one. > > you should use quote to convert the *password* to quoted form, not use it on > the entire URL. > Am sorry Fred. The same problem: File "C:\Python24\lib\httplib.py", line 598, in _set_hostport raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) httplib.InvalidURL: nonnumeric port: '|\' I dont think its an issue to be resolved with quote(). Thanks, Senthil From rudy.schockaert at gmail.com Thu Nov 23 04:52:53 2006 From: rudy.schockaert at gmail.com (Rudy Schockaert) Date: Thu, 23 Nov 2006 10:52:53 +0100 Subject: Using SimpleXMLRPCServer in a Windows Service Message-ID: <60987dac0611230152r4af42ce6mfbbaf5a4409537ee@mail.gmail.com> After some Googling I found a post of someone who wanted to do exactly as what I want to do now. There is however a problem in his code that makes the service fails after the first connection. I slightly modified his code and now I can run the service longer before I run into trouble. I then tried making the SimpleXMLRPCServer multi-threaded, hoping the problem would disappear, but no avail. The code is as follows: The commented part in the while loop is from the original code. ## XML-RPC Service import sys import win32serviceutil import win32service import win32event import win32evtlogutil import win32file import servicemanager import SimpleXMLRPCServer import SocketServer import select class OBJECT: def hello(self, text): return "Hello World (%s)" % text class ThreadedSimpleXMLRPCServer(SocketServer.ThreadingMixIn, SimpleXMLRPCServer.SimpleXMLRPCServer): pass class XMLRPCSERVICE(win32serviceutil.ServiceFramework): _svc_name_ = "XMLRPCSERVICE" _svc_display_name_ = "XMLRPCSERVICE" _svc_description_ = "XMLRPCSERVICE" def __init__(self, args): win32evtlogutil.AddSourceToRegistry(self._svc_display_name_, sys.executable, "Application") win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.hSockEvent = win32event.CreateEvent(None, 0, 0, None) self.stop_requested = 0 def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.stop_requested = 1 win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): ## Write a started event servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ' (%s)' % self._svc_name_)) server = ThreadedSimpleXMLRPCServer(("", 8080)) object = OBJECT() server.register_instance(object) self.socket = server.socket while 1: r, w, x = select.select([self.socket],[],[],10) if r == [self.socket]: server.handle_request() if self.stop_requested: self.socket.close() break #win32file.WSAEventSelect(server, self.hSockEvent,win32file.FD_ACCEPT) #rc = win32event.WaitForMultipleObjects((self.hWaitStop,self.hSockEvent), 0, win32event.INFINITE) #if rc == win32event.WAIT_OBJECT_0: # break #else: # server.handle_request() # win32file.WSAEventSelect(server,self.hSockEvent, 0) # #server.serve_forever() ## Works, but breaks the ## Write a stopped event win32evtlogutil.ReportEvent(self._svc_name_, servicemanager.PYS_SERVICE_STOPPED,0, servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_,"")) if __name__ == '__main__': win32serviceutil.HandleCommandLine(XMLRPCSERVICE) I tested with the following: import xmlrpclib import time server = xmlrpclib.ServerProxy("http://localhost:8080") for i in range(100): print server.hello("%d" % i) time.sleep(1) The loop ends with the following error: Hello World (0) ... Hello World (44) Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\DATA\TestSoap.py", line 6, in ? print server.hello("%d" % i) File "C:\Python24\lib\xmlrpclib.py", line 1096, in __call__ return self.__send(self.__name, args) File "C:\Python24\lib\xmlrpclib.py", line 1383, in __request verbose=self.__verbose File "C:\Python24\lib\xmlrpclib.py", line 1137, in request headers ProtocolError: Can someone help me in creating a windows service that allows me to handle XMLRPC request? Thanks in advance, Rudy Schockaert From fredrik at pythonware.com Wed Nov 29 17:11:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Nov 2006 23:11:27 +0100 Subject: utf - string translation In-Reply-To: <1164837136.303079.312060@j44g2000cwa.googlegroups.com> References: <1164224962.711265.198090@h48g2000cwc.googlegroups.com> <1164226304.119425.206380@h54g2000cwb.googlegroups.com> <1164232741.215312.322990@k70g2000cwa.googlegroups.com> <1164529973.299095.155940@n67g2000cwd.googlegroups.com> <1164829990.146305.92750@l39g2000cwd.googlegroups.com> <1164837136.303079.312060@j44g2000cwa.googlegroups.com> Message-ID: John Machin wrote: > Another point: there are many non-latin1 characters that could be > mapped to ASCII. For example: > u"\u0141ukasziewicz".translate(unaccented_map()) > doesn't work unless an entry is added to the no-decomposition table: > 0x0141: u"L", # LATIN CAPITAL LETTER L WITH STROKE > > It looks like generating extra entries like that could be done, with > the aid of unicodedata.name(): > > LATIN CAPITAL LETTER X WITH blahblah -> "X" > LATIN SMALL LETTER X WITH blahblah -> "X".lower() > > This would require a fair bit of care -- obviously there are special > cases like LATIN CAPITAL LETTER O WITH STROKE. Eyeballing by regional > experts is probably required. see the comments over at http://effbot.org/zone/unicode-convert.htm for an extended table, eyeballed by a regional expert (and since he makes the same point about OE vs Oe as you do, I'll probably have to change the code ;-) From fredrik at pythonware.com Sun Nov 12 19:41:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Nov 2006 01:41:40 +0100 Subject: format requires a mapping? In-Reply-To: <1163377959.646963.94900@e3g2000cwe.googlegroups.com> References: <1163377959.646963.94900@e3g2000cwe.googlegroups.com> Message-ID: ronrsr wrote: > what is python trying to tell me here? does it have to do with > formatting the string. > > Keywords and Zinger are fields in my database. > > print """ > Keywords > Zinger > > > > > > TypeError: format requires a mapping portions of your code and the traceback appears to be missing, so it's a bit hard to tell what you're really doing here, but that error message usually means that you're using the % string formatting operator with named placeholders in the string template, but with something that's not a dictionary as the data. an example: >>> "%(name)s" % 10 Traceback (most recent call last): File "", line 1, in TypeError: format requires a mapping either switch to positional markers, or put the data in a dictionary (or any other object that implements the mapping interface). From gagsl-py at yahoo.com.ar Thu Nov 9 13:45:11 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 09 Nov 2006 15:45:11 -0300 Subject: Lists of lists and tuples, and finding things within them In-Reply-To: <5f56302b0611091006k6326d724t66b654250a8b77e8@mail.gmail.co m> References: <1163079978.5053.32.camel@pepper> <5f56302b0611091006k6326d724t66b654250a8b77e8@mail.gmail.com> Message-ID: <7.0.1.0.0.20061109153335.04197f90@yahoo.com.ar> At Thursday 9/11/2006 15:06, Daniel Nogradi wrote: > > I have a program that keeps some of its data in a list of tuples. > > Sometimes, I want to be able to find that data out of the list. Here is > > the list in question: > > > > [('password01', 'unk'), ('host', 'dragonstone.org'), ('port', '1234'), > > ('character01', 'Thessalus')] > > > > > > for key, value in x: > > if key == 'host': > > print value > > > >If I were you I would use a dictionary for such a thing: > >mydict = dict( password01='unk', host='dragonstone.org', port='1234', >character01='Thessalus' ) > >And then you would look up host by: > >mydict[ 'host' ] You can even keep the original tuples, and create a dict when needed (if searches like this are seldom used): print dict(x)['host'] print dict(x).get('host') -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From Tim.Golden at viacom-outdoor.co.uk Tue Nov 28 05:55:37 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 28 Nov 2006 10:55:37 -0000 Subject: Accessing file metadata on windows XP In-Reply-To: Message-ID: [Dennis Lee Bieber] | > When rightclicking a, for example, pdf file on windows, one normally | > gets a screen with three or four tags. Clicking on one of | the summary | > tag one can get some info like "title", "Author", | "category", "keyword" | > etc.. | > | Doesn't for me... Right-clicking on a PDF gives me a | pop-up menu to open, print, compress to ZIP, send to | application in a predefined list, copy/delete/rename, | and access properties. OK, I admit I understood that to mean: rightclicking and selecting Properties (or getting the Property Sheets any other way)... | Unfortunately, you now encounter the difference between Windows | (right-click/properties/summary) data, and what PDF format itself | maintains internally Very true; there is confusion in this particular case. Not sure if the OP was simply using a PDF as an example, which could have been a .txt file for example. Or if he wanted to be specific. Good point. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From george.sakkis at gmail.com Sun Nov 12 21:34:26 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 12 Nov 2006 18:34:26 -0800 Subject: Python 3000 idea -- + on iterables -> itertools.chain References: Message-ID: <1163385266.824914.265490@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: > John Reese wrote: > > > It seems like it would be clear and mostly backwards compatible if the > > + operator on any iterables created a new iterable that iterated > > throught first its left operand and then its right, in the style of > > itertools.chain. > > you do know that "iterable" is an informal interface, right? to what > class would you add this operation? > > The base object class would be one candidate, similarly to the way __nonzero__ is defined to use __len__, or __contains__ to use __iter__. Alternatively, iter() could be a wrapper type (or perhaps mixin) instead of a function, something like: from itertools import chain, tee, islice import __builtin__ _builtin_iter = __builtin__.iter class iter(object): def __init__(self, iterable): self._it = _builtin_iter(iterable) def __iter__(self): return self def next(self): return self._it.next() def __getitem__(self, index): if isinstance(index, int): try: return islice(self._it, index, index+1).next() except StopIteration: raise IndexError('Index %d out of range' % index) else: start,stop,step = index.start, index.stop, index.step if start is None: start = 0 if step is None: step = 1 return islice(self._it, start, stop, step) def __add__(self, other): return chain(self._it, other) def __radd__(self,other): return chain(other, self._it) def __mul__(self, num): return chain(*tee(self._it,num)) __rmul__ = __mul__ __builtin__.iter = iter if __name__ == '__main__': def irange(*args): return iter(xrange(*args)) assert list(irange(5)[:3]) == range(5)[:3] assert list(irange(5)[3:]) == range(5)[3:] assert list(irange(5)[1:3]) == range(5)[1:3] assert list(irange(5)[3:1]) == range(5)[3:1] assert list(irange(5)[:]) == range(5)[:] assert irange(5)[3] == range(5)[3] s = range(5) + range(7,9) assert list(irange(5) + irange(7,9)) == s assert list(irange(5) + range(7,9)) == s assert list(range(5) + irange(7,9)) == s s = range(5) * 3 assert list(irange(5) * 3) == s assert list(3 * irange(5)) == s George From grflanagan at yahoo.co.uk Fri Nov 24 06:47:58 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 24 Nov 2006 03:47:58 -0800 Subject: Python work in UK In-Reply-To: <4565f638$0$2447$db0fefd9@news.zen.co.uk> References: <4565f638$0$2447$db0fefd9@news.zen.co.uk> Message-ID: <1164368878.498275.303570@45g2000cws.googlegroups.com> Will McGugan wrote: > Hi, > > I'd love to work in Python, for the sake of my blood pressure, but there > doesnt seem to be that many jobs that look for Python as the main skill. > I use Python at work from time to time, and occasionaly get to spend > several days on a Python project but the majority of the time I use C++. > How can I make that leap to working with Python? There doesn't seem to > be many UK positions on the jobs section of Python.org or the usual jobs > sites. Any recommended jobs sites or tips? (I have googled) > Hi Will I recommend 'cwjobs.co.uk' and 'reed.co.uk'. I got my current (Python) contract through MCG recruitment (mcg-recruitment.com), and I've just accepted a Python/Zope position through sienared.com - both of these are in London and came via CWjobs. I don't know about the rest of the country but there is definitely pure Python work in London if you look for it. Good Luck. Gerard From DustanGroups at gmail.com Sat Nov 11 21:25:36 2006 From: DustanGroups at gmail.com (Dustan) Date: 11 Nov 2006 18:25:36 -0800 Subject: reduce to be removed? In-Reply-To: References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163288885.884417.218270@f16g2000cwb.googlegroups.com> <1163290526.013063.245130@m7g2000cwm.googlegroups.com> <1163295752.701124.322620@h54g2000cwb.googlegroups.com> Message-ID: <1163298336.778941.138540@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > Dustan wrote: > > >>>> foo =\ > > [[[1,2,3],[4,5,6],[7,8,9]], > > [[3,2,1],[6,5,4],[9,8,7]]] > > > > Here, foo appears to be a 3-dimensional list - except it's supposed to > > be 2-dimensional. The inner-list-of-lists is a result of how I'm > > producing the data, and now I want to do a mass-concatenation (or > > extending) of the inner-list-of-lists, and come up with this result: > > > >>>> foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]] > > True > > that still doesn't explain your "the expression must be used in a list > comprehension" requirement, though. Oh, right; sorry about the confusion. The list isn't quite that simple, and in order to pull the right pieces together, I use a list comprehension. > assuming that the sizes are > varying, and at least sometimes a lot larger than 3x3, I'd probably > write the above as > > for index, item in enumerate(foo): > this = [] > for i in item: > this.extend(i) > foo[index] = this I'll see if that works. > which should be pretty efficient, since it avoids unnecessary function > calls, and is amortized linear time instead of O(N**2). > > or, if I was in a hurry, and didn't really care if the inner sequences > were lists or tuples: > > foo = map(Tkinter._flatten, foo) > > Steven D'Aprano wrote: > I don't know if this is the best, but it didn't take long to come up with > it: > > >>> foo = [[[1,2,3],[4,5,6],[7,8,9]], > ... [[3,2,1],[6,5,4],[9,8,7]]] > >>> > >>> def unroll(list3d): > ... newl = [] > ... for sublist in list3d: > ... newl.append(sum(sublist, [])) > ... return newl deja vu... > >>> bar = unroll(foo) > >>> bar > [[1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 2, 1, 6, 5, 4, 9, 8, 7]] > > > Repeat after me: > > "Not everything has to be a one-liner." Not everything has to be a one-liner. But readability helps. > If sum() is too slow, because your sub-lists are huge, you can easily > factor that out and replace it with something using extend. > > > -- > Steven. From johnjsal at gmail.com Thu Nov 2 11:41:47 2006 From: johnjsal at gmail.com (JohnJSal) Date: 2 Nov 2006 08:41:47 -0800 Subject: creating new objects with references to them In-Reply-To: References: <1162480549.786082.290980@b28g2000cwb.googlegroups.com> <1162482760.424782.244760@h48g2000cwc.googlegroups.com> <1162483976.152660.121200@f16g2000cwb.googlegroups.com> Message-ID: <1162485707.730939.98020@i42g2000cwa.googlegroups.com> Steve Holden wrote: > del rec[7] Hmmm, but what if the record can remain open, changes can be made, and then saved again to the same object? I suppose it isn't necessary to delete them, right? Man, this stuff gets complicated.... From martin.dion at gmail.com Fri Nov 3 16:00:13 2006 From: martin.dion at gmail.com (martdi) Date: 3 Nov 2006 13:00:13 -0800 Subject: Having trouble with file modes In-Reply-To: <1162585293.671650.94910@k70g2000cwa.googlegroups.com> References: <1162585293.671650.94910@k70g2000cwa.googlegroups.com> Message-ID: <1162587613.376486.298340@h54g2000cwb.googlegroups.com> > At first I was convinced that "w+" was the tool for the job. But now > I'm finding that the contents of the file are deleted (so I can't read > the data in). Possible File Modes: a : Append -- Add data at the end of the file r : Read -- Read from the file w : write -- Flush contents of the file and put data in it r+ : read and write -- Make changes to the file any of the above modes with b added at the end of the mode sets the file in binary mode you might want to check section 7.2 from http://docs.python.org/tut/node9.html Ofen when doing file operations you might prefer to read the file to modify, make changes in memory then save back in an other file, so you can make sure the changes are ok before you replace the old one From ronrsr at gmail.com Mon Nov 27 14:58:20 2006 From: ronrsr at gmail.com (ronrsr) Date: 27 Nov 2006 11:58:20 -0800 Subject: can't get cgi values In-Reply-To: <1164652134.826957.80980@h54g2000cwb.googlegroups.com> References: <1164652134.826957.80980@h54g2000cwb.googlegroups.com> Message-ID: <1164656772.324219.71390@h54g2000cwb.googlegroups.com> Thank you, all. that was very helpful, and did solve many of my problems. I was addressing the dict with () rather than []. I'm still having one problem, though -- extracting the keywords. NOw, if you check the value for Form below, you'll see there is more than one keyword entry. When I do: keywords = form["keywords"] - what sort of data structure do I get back? th anks so much again. -rsr- if form.has_key("keywords"): keywords = str(form["keywords"].value) else: keywords = "k" fileHandle.write("here comes keywords:") fileHandle.write(str(keywords)) fileHandle.write("keyword info"); fileHandle.write(str(form.has_key("keywords"))) fileHandle.flush() > here's the info I know: > > form = FieldStorage(None, None, [MiniFieldStorage('zid', '17'), > MiniFieldStorage('keywords', 'aAUA'), MiniFieldStorage('keywords', > 'aBOS'), MiniFieldStorage('citation', 'The Earth Times Monthly, > April 2002\\r\\n \\r\\n \r\n '), > MiniFieldStorage('quotation', 'Farm support goes mainly to a relatively > small number of agri-businesses, many of them large corps. Yet these > subsidies are 6 times what rich countries provide in foreign aid to a > developing world that includes 5 billion people.\\r\\n \r\n > '), MiniFieldStorage('updatebutton', 'Update')]) > form.has_key("citation") = True > > From craigtw.online at gmail.com Sun Nov 26 19:38:05 2006 From: craigtw.online at gmail.com (Craig) Date: 26 Nov 2006 16:38:05 -0800 Subject: Generating header information using ElementTree In-Reply-To: <1164586070.655741.256800@h54g2000cwb.googlegroups.com> References: <1164574832.936947.69420@h54g2000cwb.googlegroups.com> <1164579522.671325.36260@14g2000cws.googlegroups.com> <4suidqF10rlh1U1@mid.uni-berlin.de> <1164583078.233238.227010@45g2000cws.googlegroups.com> <1164586070.655741.256800@h54g2000cwb.googlegroups.com> Message-ID: <1164587885.050983.282680@l39g2000cwd.googlegroups.com> John Machin wrote: > Craig wrote: > > > Great. Got that sorted. The problem I have now is that some of the > > XML data is not copied across to the file when I have the text > > information included. The number of characters that is lost is equal > > to the number of characters that is in the block of text I entered > > before. The code I am using is: > > > > def WriteXMLRecord ( record, XMLFileBaseName, root): > > RecordName = SubElement(root, "Log") > > #iterate through all the fields in the record > > for key in record: > > # write the key and its data > > test = SubElement(RecordName, key) > > test.text = str(record[key]) > > tree = ElementTree(root) > > tree.write(XMLFileBaseName) > > I'm guessing, based on reading the docs for the write method, that you > should be using the file handle, rather than the file name, if the file > is already opened. So (1) change the name of the 2nd arg to > XMLFileHandle or somesuch, and in the caller, use outFile (the handle) > instead of "record.xml". > > > > > def main(): > > outFile = open("record.xml", 'w') > > outFile.write(""" > > > > \n\n""") > > > > root = Element("Log") > > WriteXMLRecord(data1, "record.xml", root) > > WriteXMLRecord(data2, "record.xml", root) > > WriteXMLRecord(data3, "record.xml", root) > > outFile.close() > > > HTH, > John Great. Got it. Thanks so much for all your help. Craig From bj_666 at gmx.net Wed Nov 8 08:07:07 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 08 Nov 2006 14:07:07 +0100 Subject: please help with optimisation of this code - update of given table according to another table References: <1162981094.820174.65440@b28g2000cwb.googlegroups.com> Message-ID: In <1162981094.820174.65440 at b28g2000cwb.googlegroups.com>, Farraige wrote: > Let's say we have a table T1: > > A B C D E > --------------- > 1 4 5 7 7 > 3 4 0 0 0 > > and we call a method mergeTable(T1, T2, [0,1], [2,4]) > > It means that we would like to update columns C and E of table T1 with > data from table T2 but only in case the key columns A and B are equal > in both tables.... I grant that the given key is unique in both tables > so if I find a row with the same key in table T2 I do merging, stop and > go to next row in table T1... > > Let's say T2 looks following: > > A B C D E > --------------- > 2 2 8 8 8 > 1 4 9 9 9 > > So after execution of our mergeTable method, the table T1 should look > like : > > A B C D E > 1 4 9 7 9 > 3 4 0 0 0 > > The 2nd row ['3', '4', '0' ,'0', '0'] didn't change because there was > no row in table T2 with key = 3 ,4 > > The main part of my algorithm now looks something like ... > > merge(t1, t2, keyColumns, columnsToBeUpdated) > > ....... > > for row_t1 in t1: > for row_t2 in t2: > if [row_t1[i] for i in keyColumns] == [row_t2[j] for j > in keyColumns]: > # the keys are the same > for colName in columnsToBeUpdated: > row_t1[colName] = row_t2[colName] > > # go outside the inner loop - we found a row with > # the same key in the table > break > > In my algorithm I have 2 for loops and I have no idea how to optimise > it (maybe with map? ) > I call this method for very large data and the performance is a > critical issue for me :( Just go through the first table once and build a mapping key->row and then go through the second table once and look for each row if the key is in the mapping. If yes: update columns. This runs in O(2*rows) instead if O(rows**2). def update_table(table_a, table_b, key_columns, columns_to_be_updated): def get_key(row): return tuple(row[x] for x in key_columns) key2row = dict((get_key(row), row) for row in table_a) for row in table_b: row_to_be_updated = key2row.get(get_key(row)) if row_to_be_updated is not None: for column in columns_to_be_updated: row_to_be_updated[column] = row[column] def main(): table_a = [[1, 4, 5, 7, 7], [3, 4, 0, 0, 0]] table_b = [[2, 2, 8, 8, 8], [1, 4, 9, 9, 9]] update_table(table_a, table_b, (0, 1), (2, 4)) for row in table_a: print row Ciao, Marc 'BlackJack' Rintsch From fredrik at pythonware.com Thu Nov 16 08:12:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 14:12:02 +0100 Subject: lxml/ElementTree and .tail In-Reply-To: References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> <761846B7-E374-41FE-8804-CBB3D42FD4D2@snowtide.com> Message-ID: Chas Emerick wrote: > The principle and the practice diverge significantly in our neck of > the woods. The current project involves consuming and making sense > of extraordinarily (and typically unnecessarily) complex XHTML. wasn't your original complaint that ET didn't do the "right thing" when you removed elements from a mixed-content tree? (something than can be trivially handled with a 2-line helper function) why mutate the tree if all you want is to extract information from it? doesn't sound very efficient to me... From Bryce.Bolton at lasp.colorado.edu Mon Nov 13 16:47:45 2006 From: Bryce.Bolton at lasp.colorado.edu (Bryce Bolton) Date: Mon, 13 Nov 2006 14:47:45 -0700 Subject: Python app links in windows In-Reply-To: <4558DBEF.8010409@hobbshouse.org> Message-ID: <000001c7076d$5de84000$9f0bf70a@lasp.colorado.edu> I want to click a link, which is assocated with a Python application in Windows, and have the contents of the link file passed to my program. How is this done? Let's say the link name is: open_database_viewform_50324.pal (pal = python application link) Inside of open_document_number_50324.pal is the following: "database_entry" "50324" So, if I have created a python application and compiled it into EXE, then associated that viewer app, in windows, with the .PAL extension, it will be called when I click any .PAL "link file". My question is: How do the contents of the link file get passed to the python application assocated with .PAL files? Are the file contents passed as an ARGV array? There must be more to this because when I open a file like some_doc.XLS, the entire contents of that file get passed to Excel, but I don't know how. Thanks, Bryce From mike.klaas at gmail.com Fri Nov 3 23:57:21 2006 From: mike.klaas at gmail.com (Klaas) Date: 3 Nov 2006 20:57:21 -0800 Subject: Defaultdict and speed In-Reply-To: <1162542563.386682.3090@b28g2000cwb.googlegroups.com> References: <1162542563.386682.3090@b28g2000cwb.googlegroups.com> Message-ID: <1162616241.354248.70220@f16g2000cwb.googlegroups.com> bearophileHUGS at lycos.com wrote: > This post sums some things I have written in another Python newsgroup. > More than 40% of the times I use defaultdict like this, to count > things: > > >>> from collections import defaultdict as DD > >>> s = "abracadabra" > >>> d = DD(int) > >>> for c in s: d[c] += 1 > ... > >>> d > defaultdict(, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}) > > But I have seen that if keys are quite sparse, and int() becomes called > too much often, then code like this is faster: > > >>> d = {} > >>> for c in s: > ... if c in d: d[c] += 1 > ... else: d[c] = 1 > ... > >>> d > {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1} > > So to improve the speed for such special but common situation, the > defaultdict can manage the case with default_factory=int in a different > and faster way. Benchmarks? I doubt it is worth complicating defaultdict's code (and slowing down other uses of the class) for this improvement... especially when the faster alternative is so easy to code. If that performance difference matters, you would likely find more fruitful gains in coding it in c, using PyDict_SET. -Mike From gagsl-py at yahoo.com.ar Mon Nov 6 18:10:56 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 06 Nov 2006 20:10:56 -0300 Subject: Wait for keyboard input In-Reply-To: References: Message-ID: <7.0.1.0.0.20061106200837.049b27c8@yahoo.com.ar> At Monday 6/11/2006 09:58, Santosh Chikkerur wrote: >How to use getchar( ) in python. I want to see the output of the >program ,step by step. >I have given print statements in between for the results.. >Hence i would like to print the output everytime there is >getchar().which is the >similar fn in python Use raw_input() and press ENTER. >When replying, please edit your Subject line so it is more specific >than "Re: Contents of Python-list digest..." Best if you follow that suggestion... -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From deets at nospam.web.de Tue Nov 21 07:37:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 21 Nov 2006 13:37:11 +0100 Subject: Reference class in class creation References: Message-ID: <4sga7nFsi0j0U1@mid.uni-berlin.de> Gregor Horvath wrote: > Hi, > > I want to reference a class itself in its body: > > class SomeElement(object): > def __init__(self, mycontainer): > self.mycontainer=mycontainer > > class SomeContainer(object): > a = SomeElement(SomeContainer) > > > Unfortunatly this does not work since the name SomeContainer is not > definied at class creation time of SomeContainer: > > /tmp/python-9309vMe.py in SomeContainer() > 4 > 5 class SomeContainer(object): > ----> 6 a = SomeElement(SomeContainer) > 7 > 8 > > NameError: name 'SomeContainer' is not defined > > > How to do this? Anything wrong with: class Foo(object): pass Foo.a = Foo ? Diez From onurb at xiludom.gro Wed Nov 15 10:59:25 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 15 Nov 2006 16:59:25 +0100 Subject: Is python for me? In-Reply-To: <1163530584.269684.214520@h48g2000cwc.googlegroups.com> References: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> <1163441468.081643.189600@f16g2000cwb.googlegroups.com> <1163448523.712403.232970@i42g2000cwa.googlegroups.com> <1163530584.269684.214520@h48g2000cwc.googlegroups.com> Message-ID: <455b395e$0$3184$426a34cc@news.free.fr> dakman at gmail.com wrote: > By large I mean an application with intensive operations, such as a > fancy GUI maybe a couple of threads, accessing a database, etc. > Threads are handled by the OS. GUI are (usually) handled by a lower-level lib like GTK or such. DB access mostly rely on the particular RDBMS. So we're left with the application code itself - the glue between all these componants. There's usually nothing really "intensive" here, and I wouldn't bet using C++ instead of Python would make a huge difference here - wrt/ perceived performances at least. My 2 cents... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sjmachin at lexicon.net Wed Nov 15 21:30:30 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 16 Nov 2006 13:30:30 +1100 Subject: Decimal() instead of float? In-Reply-To: References: <1163294604.4675.4.camel@pepper><1163322853.760315.51040@k70g2000cwa.googlegroups.com> <455b82a0$0$7054$c3e8da3@news.astraweb.com> Message-ID: <455bcd54$1@news.eftel.com> On 16/11/2006 8:57 AM, Terry Reedy wrote: > "John Salerno" wrote in message > news:455b82a0$0$7054$c3e8da3 at news.astraweb.com... >> John Machin wrote: >> >>> Here in Austraila, (I expect this is common to most countries), there >>> are people who are utterly clueless about elementary data model rules, >>> like identification "numbers" should be kept as strings. >> Do you mean that ID numbers that serve as a primary key in a database >> should also be strings? > > If you mean user-entered data like social security, phone, account, part, > or postal code 'numbers' -- as opposed to internal db-generated numbers > that the user never sees -- this I would presume 'yes'. > > tjr Clarification: A db-generated number like ROWID etc should be whatever the db makes it. An identification "number" like social security number etc should be a string, irrespective of (a) whether the user entered it or a script entered it and (b) whether it's a primary key, foreign key or no key at all. Some "numbers" contain characters outside [0-9]: e.g. ISBN (base 11, "X" means 10); Hong Kong ID card "number" (base 36 in some positions). Even if all bytes are in [0-9], a simple rule should be applied: Does it make sense to add or subtract such "numbers"? The answer with (SSN, phone number, account number, postal code) is no, so don't store it as a numeric type. Cheers, John From fredrik at pythonware.com Sun Nov 26 14:06:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 26 Nov 2006 20:06:31 +0100 Subject: acessing to the raw data of an email message In-Reply-To: <20061126193456.2bb5d97a@autremonde> References: <20061126193456.2bb5d97a@autremonde> Message-ID: Jiba wrote: > Does anyone have an idea ? I think it would be nice to let the > parser add the raw message data in the Message object. since you're the one passing the raw data to the email parser, maybe you could store it somewhere yourself? From onurb at xiludom.gro Thu Nov 9 05:50:42 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 09 Nov 2006 11:50:42 +0100 Subject: substring search without using built in utils In-Reply-To: References: Message-ID: <45530805$0$10013$426a74cc@news.free.fr> Gabriel Genellina wrote: > At Wednesday 8/11/2006 22:29, zeal elite wrote: > >> I am looking for substring search python program without using the >> built in funtions like find, or 'in'. > > The only reasonable usage for such a constraint would be a school > assignment so: don't cheat and do your homework! > OTHO, looking for existing solutions to a same or similar problem and studying them is usually considerer good practice in real-life programming jobs !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jeffrey.aylesworth at gmail.com Fri Nov 24 11:42:02 2006 From: jeffrey.aylesworth at gmail.com (jeff) Date: 24 Nov 2006 08:42:02 -0800 Subject: reading id3 tags with python In-Reply-To: <1164354948.000349.52170@m7g2000cwm.googlegroups.com> References: <1164328566.089711.89870@l12g2000cwl.googlegroups.com> <1164354948.000349.52170@m7g2000cwm.googlegroups.com> Message-ID: <1164386522.229372.116120@l12g2000cwl.googlegroups.com> well, heres the error:: ###### Traceback (most recent call last): File "./main.py", line 28, in ? info = id3.Reader(file) File "/home/jeffrey/Documents/Music/.rename/id3reader.py", line 187, in __init__ self._readId3() File "/home/jeffrey/Documents/Music/.rename/id3reader.py", line 306, in _readId3 self._interpretFlags() File "/home/jeffrey/Documents/Music/.rename/id3reader.py", line 341, in _interpretFlags self._readExtHeader = _readExtHeader_rev3 NameError: global name '_readExtHeader_rev3' is not defined #### also, i didnt account for Y/N/Yes/No, whatever because this script is just for myself (also why i didnt use that function to join pathnames, i oonly realy use linux anymore) and what do you mean by 'id3reader' cant do directories? my for loop just does each file in the dirextory From tleeuwenburg at gmail.com Tue Nov 28 22:50:51 2006 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 28 Nov 2006 19:50:51 -0800 Subject: 6 Pick Bet Grouping In-Reply-To: <1164768957.528355.210070@16g2000cwy.googlegroups.com> References: <1164768957.528355.210070@16g2000cwy.googlegroups.com> Message-ID: <1164772251.325678.45990@l39g2000cwd.googlegroups.com> bullockbefriending bard wrote: > (I apologise in advance for posting something slightly OT, but plead in > mitigation that I'm trying to re-write an old, suboptimal VB6 (erk) > brute-force attack in a shiny, elegant, pythonic manner. I would really > appreciate some ideas about an appropriate algorithmic approach to this > + pointers to any relevant implementations in Python. Along the way, > I'm also trying to get Python into my organisation through the back > door - so a further plea for tolerance in posting this here! :)) > > A single 6 Pick bet looks like this: > RACE1 RACE2 RACE3 RACE4 RACE5 RACE6 > runner1 / runner 2 / runner 3 / runner4 / runner5 / runner6 - $amount > > e.g. we might have: > > 5 / 3 / 11 / 7 / 1 / 9 - $50 (5 to come 1st or 2nd in Race1, 3 to > come first or 2nd in Race 2, etc.) > 7 / 3 / 11 / 7 / 1 / 9 - $50 > 5 / 3 / 11 / 14 / 1 / 9 - $50 > 7 / 3 / 11 / 14 / 1 / 9 - $50 > > The totalizator system allows us to merge or group these four bets as > follows: > > 5 + 7 / 3 / 11 / 7 + 14 / 1 / 9 - $50 ($200 total) > > This method of expressing multiple bets in one line is advantageous > because we may have many thousands of combinations we wish to bet and > only a limited amount of time in which to bet them. > > There are up to 14 horses in each race, so 7,529,536 possible 6 Pick > bets. In practice, one might wish to bet (say)15,000 combinations out > of these 7.5 million. However, it would be very nice to be able to > *optimally* merge (as shown above) these 15,000 combinations so that > they might fit on (say) 2,000 betting tickets instead of trying to > write out 15,000 single tickets. > > To keep things simple, let's assume that all single bets are for the > same amount. (In practice, however, this is not so.) > > Now, it's certainly possible to go about this via brute force > iteration, but I would really appreciate it if anyone with a CS > background could point me toward a smarter plan of attack. I have > perused Skiena's Algorithm Handbook and various websites and can't seem > to find an analogous problem. I'm hoping this is just my ignorance and > that my brief exposition rings a bell for someone here. I don't understand exactly. Why not merge all your bets into a single line? What constraints exist on how many bets you can put onto one ticket? Do you meant you have some bag full of incoming bets, which you are re-lodging after some merging process? Does this mean you will have one ticket for each amount? Cheers, -T From mike at mikeash.com Wed Nov 8 22:17:27 2006 From: mike at mikeash.com (Michael Ash) Date: Wed, 08 Nov 2006 21:17:27 -0600 Subject: Using Python from Cocoa App via PyObjc - numbers dont match... References: <1163035378.654266.287360@m73g2000cwd.googlegroups.com> Message-ID: <1163042247.489957@nfs-db1.segnet.com> In comp.lang.objective-c sapsi wrote: > The first output in the console is 40.4 and the second > -40.40000152587891. > > If i change the NSLog(s) to "%f",[n floatValue] (and the second > likewise) the first is 40.400002 and the second is -40.400002. I assume you are complaining about the fact that it's not printing exactly 40.4, and wondering where the error is coming from. (It helps if you actually state this yourself, so we don't have to assume it, rather than just laying out the circumstances.) The answer is that floating point numbers are inherently imprecise. Read through this essential resource: http://docs.sun.com/source/806-3568/ncg_goldberg.html -- Michael Ash Rogue Amoeba Software From markscottwright at gmail.com Thu Nov 23 06:32:45 2006 From: markscottwright at gmail.com (markscottwright) Date: 23 Nov 2006 03:32:45 -0800 Subject: Abelson and Python In-Reply-To: References: <1164239517.067445.179320@e3g2000cwe.googlegroups.com> <1164246961.951287.132170@j44g2000cwa.googlegroups.com> Message-ID: <1164281565.180846.232360@k70g2000cwa.googlegroups.com> Fredrik Lundh wrote: > markscottwright wrote: > > > If it were that easy, the PyPy guys would be done by now. > > if the PyPy guys had focused on writing a Python interpreter in Python, > they'd been done by now. > > Isn't that the point of PyPy? It's what their mission statement says (http://codespeak.net/pypy/dist/pypy/doc/architecture.html#mission-statement): "PyPy is an implementation of the Python programming language written in Python itself, flexible and easy to experiment with." This is something that is amazingly easy to do in scheme, since the language is so simple, but is typically pretty difficult to do in other languages. I remember being blown away by how much I knew after reaching the end of SICP - I wanted to go out and write my own scheme compiler (and given the proliferation of scheme implementations, a lot of other people must have felt the same way). I don't remember getting to the end of a book on python and thinking, "that's easy. I could do that!" That said, I see now that the course we're talking about isn't the same as the old 6.001 course, and presumably has different pedagogical goals. From theller at ctypes.org Fri Nov 3 17:48:17 2006 From: theller at ctypes.org (Thomas Heller) Date: Fri, 03 Nov 2006 23:48:17 +0100 Subject: py2exe questions In-Reply-To: <454BB574.9030607@websafe.com> References: <454BB574.9030607@websafe.com> Message-ID: <454BC731.3000805@ctypes.org> Larry Bates schrieb: > Doug Stell wrote: >> I have 2 questions about py2exe or any similar utility. >> >> 1. Is it possible to create a single Windows executable that does not >> blow out to a folder full of files and can be called from scripts >> using command line arguments? >> >> 2. If the above can be done, it is possible to hide parts of the >> Python source code from users? These users are software developers, >> but we don't want them to see how the code does what it does. >> >> thanks, doug > > py2exe reduce the number of files you need to distribute down to 4: > > msvcr71.dll > w9xpopen.exe (Windows/98 support) > library.zip (all .pyo, .pyd, and .dll files) > applcation.exe It can easily be reduced to 2 files by 'embedding' the libray.zip into the exe (use the zipfile=None option), and deleting the w9xpopen.exe if you don't need win98 support. > I does not however go to great lengths to "hide" the code from > someone with time/expertise that wants to get to your code > (but then just about anything can be disassembled). The compiled > .pyo files are just placed in library.zip. At least it doesn't > send your .py files along. Thomas From steve at holdenweb.com Wed Nov 8 14:02:16 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 08 Nov 2006 13:02:16 -0600 Subject: Exception Handling in TCPServer (was; Problem exiting application in Windows Console.) In-Reply-To: <1163007018.221972.93580@b28g2000cwb.googlegroups.com> References: <1162987854.490880.46820@h54g2000cwb.googlegroups.com> <1163001245.707034.310900@f16g2000cwb.googlegroups.com> <1163007018.221972.93580@b28g2000cwb.googlegroups.com> Message-ID: Ant wrote: > Ant wrote: > .... >> OK, I've narrowed the problem back to the way HTTPServer (actually its >> TCPServer parent) handles exceptions thrown by the process_request >> method by catching them all, and then calling a handle_error method. >> There doesn't seem to be a way of getting at the exception thrown >> however - does anyone know how I can get this information? > > Hmm. Lonely topic ;-) > > I've found a way to solve the problem, by creating a subclass of > HTTPServer which overrides the handle_error method: > > class HelpServer(HTTPServer): > def handle_error(self, request, client_address): > exception_line = inspect.trace()[-1][-2][0] > if "sys.exit" in exception_line: > print "Trying to exit again!" > sys.exit(0) > else: > HTTPServer.handle_error(self, request, client_address) > > This seems a really nasty hack though - any ideas for a cleaner way to > do it? > First of all, five hour response time is a high expectation, you must be a Platinum customer :-) Secondly, while a try/except catching all exceptions *is* unusual it's justifiable in a server context (though some logging and/or analysis certainly wouldn't go amiss). Thirdly your "ugly hack" *could* be replaced by something cleaner with more analysis of the trace structure, but given how infrequently this code is going to run and the low probability that anything else will trigger the hook I'd be happy with it as it is. But that's just me ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From pruebauno at latinmail.com Wed Nov 1 14:31:28 2006 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: 1 Nov 2006 11:31:28 -0800 Subject: compiling on AIX 5.3 with vacpp References: <1161895884.160561.308020@e3g2000cwe.googlegroups.com> <1162005830.878986.204250@m73g2000cwd.googlegroups.com> Message-ID: <1162409488.718356.38600@e3g2000cwe.googlegroups.com> nnorwitz at gmail.com wrote: > pruebauno at latinmail.com wrote: > > I am trying to compile Python 2.5 on AIX 5.3. I used > > > > building '_locale' extension > > ./Modules/ld_so_aix xlc_r -q64 -bI:Modules/python.exp > > build/temp.aix-5.3-2.5/home/pxadm/.test/Python-2.5/Modules/_localemodule.o > > -L/usr/local/lib -o build/lib.aix-5.3-2.5/_locale.so > > ld: 0711-317 ERROR: Undefined symbol: .bindtextdomain > > ld: 0711-317 ERROR: Undefined symbol: .textdomain > > ld: 0711-317 ERROR: Undefined symbol: .dcgettext > > ld: 0711-317 ERROR: Undefined symbol: .dgettext > > ld: 0711-317 ERROR: Undefined symbol: .gettext > > The problem is that an additional library is needed to link the locale > module. You will first need to determine what library is needed. > Maybe libintl? To find out, you can do a man on any of those symbols, > for example, man textdomain. > > That should tell you want library is required. You will then need to > modify setup.py to add the extra library for the locale module. > There's already some support for this in setup.py around line 390: > > # access to ISO C locale support > data = open('pyconfig.h').read() > m = re.search(r"#s*define\s+WITH_LIBINTL\s+1\s*", data) > if m is not None: > locale_libs = ['intl'] > else: > locale_libs = [] > if platform == 'darwin': > locale_extra_link_args = ['-framework', 'CoreFoundation'] > else: > locale_extra_link_args = [] > > > exts.append( Extension('_locale', ['_localemodule.c'], > libraries=locale_libs, > extra_link_args=locale_extra_link_args) > ) > > Once you get something working, please post a patch. > > n Thanks for the info Neil, sorry for taking long to answer. This is skunkwork, I am working on it whenever I get some time. indeed as you say. libintl.h is required so I hard coded it into setup.py to no effect. At what point does setup.py get called? by make? my code # access to ISO C locale support data = open('pyconfig.h').read() m = re.search(r"#s*define\s+WITH_LIBINTL\s+1\s*", data) if m is not None: locale_libs = ['intl'] else: locale_libs = [] if platform == 'darwin': locale_extra_link_args = ['-framework', 'CoreFoundation'] else: locale_extra_link_args = [] locale_libs=['intl'] exts.append( Extension('_locale', ['_localemodule.c'], libraries=locale_libs, extra_link_args=locale_extra_link_args) ) From larry.bates at websafe.com Wed Nov 29 12:48:53 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 29 Nov 2006 11:48:53 -0600 Subject: Using Python In-Reply-To: References: Message-ID: beemer328i2004 wrote: > Hi Guys, > > I am new to this language and i need some help... > > I am trying to create a script that will go into a log file and bring > me back the xml from an order... > > For example: > > go into Log1.xml and extract order number 2 from top to bottom and > extract it into a txt file... > > Does anyone know how i can create this type of script or has like a > sample that i can use.. I am having a hard time starting the script.. > > hope someone can help > > Thanks agian > You should also review this module for parsing your XML: http://effbot.org/zone/element-index.htm elementree is now part of the standard library. Note: It would also help if you would post contents of log1.xml so others could see what you are working with. You should also post whatever python code you have tried so far. -Larry From larry.bates at websafe.com Sat Nov 18 14:22:44 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 18 Nov 2006 13:22:44 -0600 Subject: [Zopyrus] A python IDE for teaching that supports cyrillic i/o In-Reply-To: References: <20061118190104.GA29614@58sirius016.dc.ukrtel.net> Message-ID: Oleg Broytmann wrote: > On Sat, Nov 18, 2006 at 09:01:04PM +0200, Kirill Simonov wrote: >> Could anyone suggest me a simple IDE suitable for teaching Python as a >> first programming language to high school students? > > Does it have to be an IDE? Wouldn't it be better to use a simple text > editor + command line? > > Oleg. Not sure about cyrillic and I don't mean if you are looking for Windows IDE, but I'm impressed with Pyscripter: http://mmm-experts.com/Products.aspx?ProductId=4 -Larry From JohnRoth1 at jhrothjr.com Thu Nov 2 08:15:18 2006 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 2 Nov 2006 05:15:18 -0800 Subject: other ways to check for ? In-Reply-To: References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> Message-ID: <1162473318.495571.55550@h54g2000cwb.googlegroups.com> Fredrik Lundh wrote: > elderic wrote: > > > are there other ways than the ones below to check for > > in a python script? > > callable(f) > > PEP 3100 specifies that the callable builtin is to be removed in Python 3.0, together with what I presume is the underlying C support for the function. Unfortunately, there are cases where it's not advisable to call something to verify that it's callable - calling it will cause irreversable changes to the program state, while a verification function should make no changes to state. The advice is fundamentally bad design. On the other claw, I can understand Guido's point in wanting to get rid of it - it's got to be an ugly piece of code with the Inappropriate Intimacy code smell stinking up the place. So what to do? Frankly, I'd back up a few yards and consider the system design. Where is the callable coming from? If it's inside the team's scope of control, don't bother checking it - the team should have tests in place that verify that each site passing a callable is passing the correct object. If it's coming from outside, define what's allowable and check that case by case, preferably with consultation with your code's clients. John Roth From bdesth.quelquechose at free.quelquepart.fr Wed Nov 15 19:19:08 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 16 Nov 2006 01:19:08 +0100 Subject: Python v PHP: fair comparison? In-Reply-To: <1163605597.576368.243640@f16g2000cwb.googlegroups.com> References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163605597.576368.243640@f16g2000cwb.googlegroups.com> Message-ID: <455ba985$0$7759$426a74cc@news.free.fr> walterbyrd a ?crit : > Larry Bates wrote: > > >>I'd be surprised if there was more demand for PHP developers >>than Python developers. > > > Prepare to be surprised. From what I have seen demand for PHP > developers is off-the-scale higher than demand for Python developers. Anyone that knows how to program and understand the http protocol is already a PHP developer. > If you search the job boards, then -IMO- it is only fair to not include > jobs where the language is listed as an also-ran. Then you'll find *very* few "Python developper" jobs. > For example a typical > sys-admin job will list about 24 skills, and python is often thrown > into the landry list. To my way of thinking, that is not really an ad > for a python developer. No, it's an ad for a sys-admin job. FWIW, I've been hired as a web developer - not as a PHP or Java or whatever specific language programmer. Python wasn't even on the "landry list". Then we had to hire another developer to help me on a Zope-based project. We didn't hired a "Zope developer", nor even a "Python developer" - we hired a young C/Perl hacker with almost no prior web programming knowledge. Why ? Because he obviously was the best *programmer* we could find. As a matter of fact, he managed to become a productive Zope/Python programmer in less than two weeks. > Trying to be as fair as I can be, my research shows that demand for > developers where PHP is the primary is *far* higher than jobs where > Python is the primary skills. There are companies that believe that there are such things as "PHP programmer", "Java programmers", etc. And there are companies that know the difference between a programmer and a code-monkey. The first one will ask for 10+ years of experience on a techno that is less than 5 years old. The other will know a good coder when they meet one. Guess where are most 'Python programmers' working ? > Of course, at best, that only shows the demand part of the equation. Not even. > There is also the supply side to consider. From what I have seen for > salary offers for PHP developers, it may be fair to say that PHP > developers are a dime a dozen. > Anyone that knows how to program and understand the http protocol is already a PHP developer. From bignose+hates-spam at benfinney.id.au Tue Nov 7 17:45:07 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 08 Nov 2006 09:45:07 +1100 Subject: assigning values in __init__ References: <454faf57$0$12993$c3e8da3@news.astraweb.com> <4550daa6$0$26446$c3e8da3@news.astraweb.com> Message-ID: <877iy6oozw.fsf@benfinney.id.au> John Salerno writes: > But I do like Steve's suggestion that it's better to be explicit > about each attribute, instead of just accepting a list of numbers > (but I can't help but feel that for some reason this is better, > because it's more general). If you pass a *mapping* of the "I-might-want-to-add-more-in-the-future" values, then you get both explicit *and* expandable, without an arbitrary unneeded sequence. -- \ "He may look like an idiot and talk like an idiot but don't let | `\ that fool you. He really is an idiot." -- Groucho Marx | _o__) | Ben Finney From fredrik at pythonware.com Mon Nov 20 12:58:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Nov 2006 18:58:32 +0100 Subject: ElementSOAP and In-Reply-To: <1164043598.088253.29790@m73g2000cwd.googlegroups.com> References: <1164007864.239490.20810@k70g2000cwa.googlegroups.com> <1164043598.088253.29790@m73g2000cwd.googlegroups.com> Message-ID: mirandacascade at yahoo.com wrote: > May I confirm the following recommendations/dependencies: > 1) if one wants to use ElementSOAP to create a message that includes > , it is recommended that one use the 0.5 release of > ElementSOAP yes. or if you prefer not to upgrade, you can hack the "call" method to insert a header at the right place. > 2) if one wants to use the 0.5 release of ElementSOAP, one should be > using Python 2.5 no. but if you're using earlier versions of Python, you also need a version of ElementTree that supports the "iterparse" interface (which means 1.2.5 or later). From tim.hochberg at ieee.org Fri Nov 17 08:21:49 2006 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Fri, 17 Nov 2006 06:21:49 -0700 Subject: numpy magic: cast scalar returns auto to python types float & int ? In-Reply-To: References: Message-ID: robert wrote: > Turning algs for old NumPy modules into numpy code I suffer from this: > Upon further processing of returns of numpy calculations, lots of data in an apps object tree will become elementary numpy types. > First there is some inefficiency in calculations. And then you get data inflation and questionable dependencies - e.g. with pickle,ZODB,mpi's ... : > > >>>> l=array((1.,0)) >>>> l.prod() > 0.0 >>>> cPickle.dumps(_) > "cnumpy.core.multiarray\nscalar\np1\n(cnumpy\ndtype\np2\n(S'f8'\nI0\nI1\ntRp3\n(I2\nS'<'\nNNNI-1\nI-1\ntbS'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\ntRp4\n." >>>> cPickle.dumps(0.0) > 'F0\n.' >>>> l=array((1,0)) >>>> l.prod() > 0 >>>> cPickle.dumps(_) > "cnumpy.core.multiarray\nscalar\np1\n(cnumpy\ndtype\np2\n(S'i4'\nI0\nI1\ntRp3\n(I2\nS'<'\nNNNI-1\nI-1\ntbS'\\x00\\x00\\x00\\x00'\ntRp4\n." >>>> cPickle.dumps(0) > 'I0\n.' >>>> type(l.prod()) > > > > To avoid this you'd need a type cast in Python code everywhere you get scalars from numpy into a python variable. Error prone task. Or check/re-render your whole object tree. > Wouldn't it be much better if numpy would return Python scalars for float64 (maybe even for float32) and int32, int64 ... where possible? (as numarray and Numeric did) > I suppose numpy knows internally very quickly how to cast. The short answer is no, it would not be better. There are some trade offs involved here, but overall, always returning numpy scalars is a significant improvement over returning Python scalars some of the time. Which is why numpy does it that way now; it was a conscious choice, it didn't just happen. Please search the archives of numpy-discussion for previous discussions of this and if that is not enlightening enough please ask at on the numpy-discussion list (the address of which just changed and I don't have it handy, but I'm sure you can find it). For your particular issue, you might try tweaking pickle to convert int64 objects to int objects. Assuming of course that you have enough of these to matter, otherwise, I suggest just leaving things alone. -tim From steve at holdenweb.com Thu Nov 9 12:11:01 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Nov 2006 11:11:01 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: <1163089657.164900.112820@f16g2000cwb.googlegroups.com> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> Message-ID: <45536125.8000409@holdenweb.com> Paul Boddie wrote: > Michael Hobbs wrote: >> I think the colon could be omitted from every type of compound >> statement: 'if', 'for', 'def', 'class', whatever. Am I missing anything? > > The FAQ answer. ;-) > > http://www.python.org/doc/faq/general/#why-are-colons-required-for-the-if-while-def-class-statements > > Paul > I suppose it would be even better if that hyperlink actually took you to section 1.4.27 rather than 1.4.14 ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From john106henry at hotmail.com Thu Nov 16 23:19:50 2006 From: john106henry at hotmail.com (John Henry) Date: 16 Nov 2006 20:19:50 -0800 Subject: How fuzzy is get_close_matches() in difflib? In-Reply-To: References: <1163724049.225348.118020@h54g2000cwb.googlegroups.com> Message-ID: <1163737190.118975.227740@h48g2000cwc.googlegroups.com> I did try them and I am impressed. It helped me found a lot of useful info. I just want to get a feel as to what constitutes a "match". Steven D'Aprano wrote: > On Thu, 16 Nov 2006 16:40:49 -0800, John Henry wrote: > > > I am just wondering what's with get_close_matches() in difflib. What's > > the magic? How fuzzy do I need to get in order to get a match? > > > Why don't you try it and see? > > >>> from difflib import get_close_matches > >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"]) > ['apple', 'ape'] > >>> import keyword as _keyword > >>> get_close_matches("wheel", _keyword.kwlist) > ['while'] > >>> get_close_matches("apple", _keyword.kwlist) > [] > >>> get_close_matches("accept", _keyword.kwlist) > ['except'] > > > Those example, by the way, come from here: > > >>> help(get_close_matches) > > > > > -- > Steven From prouleau001 at gmail.com Wed Nov 29 14:26:40 2006 From: prouleau001 at gmail.com (prouleau001 at gmail.com) Date: 29 Nov 2006 11:26:40 -0800 Subject: Surprise with special floating point values In-Reply-To: References: <1164822818.252321.132680@j72g2000cwa.googlegroups.com> Message-ID: <1164828400.048314.71240@l12g2000cwl.googlegroups.com> On Nov 29, 1:11 pm, Fredrik Lundh wrote: > prouleau... at gmail.com wrote: > > While trying to use simplejson under Python 2.4.3 I have been > > investigating the handling of special floating point valuesnote that JSON doesn't support non-numeric floating point values, as can > be seen by the "number" syntax description on this page: > > http://www.json.org/ > > (and as I pointed out in another thread on this topic, Python relies on > the C library for serialization of floats, so non-numeric floating point > values aren't portable between Python versions either). > > That's true, but I ran into a problem with simplejson under Python 2.4.3 on Win32, where it fails to serialize 1.0 properly (and I reported the problem to its author, and the fact that it works fine under Python 2.5). There is another thread (Inconsistency producing constant for float "infinity") that talks about differences between Python 2.5 and earlier versions regarding treatment of non-numeric floating point values. So, while investigating the simplejson problem, I though I had found a problem with the handling of NaN (which obviously is not the case). - Pierre R. From rpdooling at gmail.com Wed Nov 22 00:36:50 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 21 Nov 2006 21:36:50 -0800 Subject: Caution newbie question: python window to stay open ? In-Reply-To: <1164165632.072406.111580@f16g2000cwb.googlegroups.com> References: <1164165632.072406.111580@f16g2000cwb.googlegroups.com> Message-ID: <1164173810.364479.223490@m7g2000cwm.googlegroups.com> mkengel wrote: > Caution: newbie question If you're pretty sure it's a common newbie question, then begin by going to the Google repository at: http://groups.google.com/group/comp.lang.python Search in the box at upper right, on, say, keep cmd window open, or keep dos window open. Like so: http://tinyurl.com/yfbtgx And you'll have answers going all the way back to antiquity. rd From gagsl-py at yahoo.com.ar Mon Nov 27 21:57:48 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 27 Nov 2006 23:57:48 -0300 Subject: combining the path and fileinput modules SOLVED In-Reply-To: <4569182C.4040206@mac.com> References: <1164291336.523872.131610@h54g2000cwb.googlegroups.com> <4565BC89.9060901@mac.com> <7.0.1.0.0.20061124234209.03442fe0@yahoo.com.ar> <4567B532.4030906@mac.com> <7.0.1.0.0.20061125034101.01f7acb0@yahoo.com.ar> <4569182C.4040206@mac.com> Message-ID: <7.0.1.0.0.20061127235518.04cc2370@yahoo.com.ar> At Sunday 26/11/2006 01:29, wo_shi_big_stomach wrote: >for line in fileinput.input(g, inplace=1, backup='.bak'): ># just print 2nd and subsequent lines > if not fileinput.isfirstline(): > print line.rstrip('\n') > # check first line only > elif fileinput.isfirstline(): > if not re.search('^From ',line): > print line.rstrip('\n') Just a note: the elif is redundant, use a simple else clause. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From torriem at chem.byu.edu Sat Nov 4 23:25:04 2006 From: torriem at chem.byu.edu (Michael Torrie) Date: Sat, 04 Nov 2006 21:25:04 -0700 Subject: WebScraping In-Reply-To: References: <454d0fb1$0$11970$afc38c87@news.optusnet.com.au> Message-ID: <1162700705.2121.4.camel@enterprise.local.lan> On Sun, 2006-11-05 at 13:40 +1100, Steven D'Aprano wrote: > On Sun, 05 Nov 2006 08:09:52 +1000, Graham Feeley wrote: > > > Can someone steer me to scripts / modules etc on webscraping please??? > > The definitive documentation on the built-in Python modules can be found > here: http://docs.python.org/modindex.html > > The ActiveState Python cookbook should be useful, e.g. > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/391929 > > Also see Beautiful Soup: > http://www.crummy.com/software/BeautifulSoup/ Beautiful soup is not always speedy, but it sure is the most flexible scraper I've ever came across. I hacked together a web forum-to-nntp gateway using Beautiful Soup. Worked very well. Michael > > And of course, GIYF ("Google Is Your Friend") http://www.google.com which > leads me to: > > http://sig.levillage.org/?p=588 > http://sig.levillage.org/2005/03/11/web-scraping-with-python-part-ii/ > http://wiki.tcl.tk/2915 (not focused on Python, but may still be useful). > > > > Ultimately I would like someone to write a script for me. > > Are you offering to hire a developer? > > > -- > Steven. > From bignose+hates-spam at benfinney.id.au Sun Nov 12 04:38:31 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 12 Nov 2006 20:38:31 +1100 Subject: Decimal() instead of float? References: <1163294604.4675.4.camel@pepper> Message-ID: <87ejs9hunc.fsf@benfinney.id.au> "Steven D'Aprano" writes: > On Sun, 12 Nov 2006 02:31:04 +0100, Fredrik Lundh wrote: > > (who uses fractional ZIP codes, btw?) > > Well, I can't speak for Americans, but here in Australia we > typically give our post codes to six decimal places: > > Melbourne 3000.000000 > Brunswick 3056.000000 > Clifton Hill 3068.000000 > Sydney 2000.000000 > St Johns Park 2176.000000 Yeah, I know. As soon as that legislation came in, I started giving the *precision* they asked for, with my own choice of *accuracy*, just to mess with their damned totalitarian databases. Melbourne 3000.000000 Brunswick 3000.000000 Clifton Hill 3000.000000 But you try to tell people overseas about this legislation, and they just don't believe you. -- \ "It is well to remember that the entire universe, with one | `\ trifling exception, is composed of others." -- John Andrew | _o__) Holmes | Ben Finney From johnjsal at NOSPAMgmail.com Tue Nov 7 16:15:19 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 07 Nov 2006 16:15:19 -0500 Subject: sqlite query not working In-Reply-To: References: <4550f36e$0$8780$c3e8da3@news.astraweb.com> Message-ID: <4550f7a5$0$14445$c3e8da3@news.astraweb.com> Steve Holden wrote: > Have you tried adding a self.connection.commit() to the code? I don't > know whether sqlite is transactional, but if it is then the changes will > disappear without a commit. Wow, that worked! Now, I know I've done some DB work before (very similar to this) and never used commit(), so I'm confused but still grateful! :) Thanks! From fuzzyman at gmail.com Sat Nov 18 18:46:34 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 18 Nov 2006 15:46:34 -0800 Subject: decompiler In-Reply-To: References: <1163822905.706713.216940@e3g2000cwe.googlegroups.com> Message-ID: <1163893594.341657.248720@k70g2000cwa.googlegroups.com> John Bokma wrote: > "jim" wrote: > > > Is there such thing as a free decompile that I can run in windows xp > > You asked the same Q in comp.lang.perl.misc... That's terrible. You read comp.lang.perl.misc *as well* ? ;-) Fuzzyman http://www.voidspace.org.uk/index2.shtml From nitte.sudhir at gmail.com Fri Nov 3 17:16:20 2006 From: nitte.sudhir at gmail.com (kath) Date: 3 Nov 2006 14:16:20 -0800 Subject: how do I pass values between classes? Message-ID: <1162592180.494470.257040@h54g2000cwb.googlegroups.com> hi everyone......... I have a task, I have fragmented the task into subtask. I have planned to create a class to each subclass and one parent class to handle the sub tasks. Each subclass are saved in seperate file and all my subclasses and parent class are placed in the same folder. The parent class is subclass of wx.Frame, and subclasses are subclass of wx.Panel. Each subclass will create a GUI for each task.. ok.. here is problem When a menu is selected in the parent class, im instantiating the child class(i.e, Panel), which has textbox and two buttons. first button is used to select a file, and second one I have planned to, read the file and pass the values to parent class [B]OR[/B] pass the filepath to parent to read and do rest of the work. How do I do that? Please tell me whether I am following a correct method, by fragmenting task into small task and assigning it to child class and saving it in a separate file?. ok, here is the Parent class [code] import wx import client """My Parent class""" class Parent(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) menu=wx.Menu() menu.Append(5000, "File") menu.AppendSeparator() menu.Append(5001, "Exit") menubar=wx.MenuBar() menubar.Append(menu, "File") self.SetMenuBar(menubar) self.Bind(wx.EVT_MENU, self.OnFile,id=5000) self.Bind(wx.EVT_MENU, self.OnExit,id=5001) def OnFile(self, event): self.cl=client.Child(self, -1) def OnBrowse(self, event): dir="" d=x.FileDialog(self, "Choose an Excel file", self.dirname, "", "*.xls", wx.OPEN) if d.ShowModal() == wx.ID_OK: self.filename=d.GetFilename() self.dirname=d.GetDirectory() self.filepath.SetValue(os.path.join(self.dirname, self.filename)) def OnUpload(self, event): pass def OnExit(self, event): self.Close() class MyApp(wx.App): def OnInit(self): frame=Parent(None, -1, "Parent window") frame.Show(True) self.SetTopWindow(frame) return True if __name__ == '__main__': app=MyApp(redirect=False) app.MainLoop() [/code] and Child class [code] import wx, os """My Child class""" class Child(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id, size=(300,300)) box=wx.BoxSizer(wx.HORIZONTAL) label=wx.StaticText(self, -1, "File Path: ") self.text=wx.TextCtrl(self, -1) browse=wx.Button(self, -1,"Browse") upload=wx.Button(self, -1, "Upload") self.Bind(wx.EVT_BUTTON, self.OnBrowse, browse) self.Bind(wx.EVT_BUTTON, self.OnUpload, upload) box.Add(label) box.Add(self.text) box.Add(browse) mainbox=wx.BoxSizer(wx.VERTICAL) mainbox.Add(box) mainbox.Add(upload) self.SetSizer(mainbox) mainbox.Layout() def OnBrowse(self, event): self.dir="" d=wx.FileDialog(self, "Choose an Excel file", self.dir, "", "*.xls", wx.OPEN) if d.ShowModal() == wx.ID_OK: self.filename=d.GetFilename() self.dir=d.GetDirectory() self.text.SetValue(os.path.join(self.dir, self.filename)) def OnUpload(self, event): pass class MyApp(wx.App): def OnInit(self): frame=wx.Frame(None, -1, "Child window") panel=Child(frame, -1) frame.Show(True) self.SetTopWindow(frame) return True if __name__ == '__main__': app=MyApp() app.MainLoop() [/code] thank you, regards, kath. From duncan.booth at invalid.invalid Thu Nov 23 06:52:20 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Nov 2006 11:52:20 GMT Subject: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]? References: Message-ID: Steven D'Aprano wrote: > No, you will never get two objects existing at the same time with the > same id. You will get two objects that exist at different times with > the same id, since ids may be reused when the object is deleted. > I think it is worth pointing out that this is an area where people get confused quite often; it is very easily to get misleading results when you call the id() function. e.g. >>> class C: def f(self): pass def g(self): pass >>> c = C() >>> id(c.f)==id(c.g) True >>> c.f is c.g False The ids are the same here only because the objects do not exist at the same time. In the first comparison c.f is an expression which creates a temporary object that is destroyed before the expression involving c.g is evaluated, so it is possible for the different objects to have the same id. In the second comparison the objects exist at the same time so they are forced to have different ids. From vedran at v-programs.com Wed Nov 1 10:25:59 2006 From: vedran at v-programs.com (vedran at v-programs.com) Date: 1 Nov 2006 07:25:59 -0800 Subject: Beginning setup problem Message-ID: <1162394759.233035.21380@f16g2000cwb.googlegroups.com> Hello again, Before few months,I write to this mailing list with python script install problem,but nobody give me right solution.I work on windows XP,and Python 2.4. Now,when I write in Python 2.4: >>> from distutils.core import setup >>> setup(......) # whatever I write I got the error: Traceback (most recent call last): File "", line 1, in -toplevel- setup() File "C:\Python24\distutils\core.py", line 101, in setup _setup_distribution = dist = klass(attrs) File "C:\Python24\distutils\dist.py", line 130, in __init__ setattr(self, method_name, getattr(self.metadata, method_name)) AttributeError: DistributionMetadata instance has no attribute 'get___doc__' When I run setup.py with CMD: python setup.py install (or build or install) Again I got the error: Traceback (most recent call last): File "", line 1, in -toplevel- setup() File "C:\Python24\distutils\core.py", line 101, in setup _setup_distribution = dist = klass(attrs) File "C:\Python24\distutils\dist.py", line 130, in __init__ setattr(self, method_name, getattr(self.metadata, method_name)) AttributeError: DistributionMetadata instance has no attribute 'get___doc__' Regards, Vedran, v-programs From bdelmee at advalvas._REMOVEME_.be Thu Nov 9 06:43:04 2006 From: bdelmee at advalvas._REMOVEME_.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Thu, 09 Nov 2006 12:43:04 +0100 Subject: cx_Oracle and NCLOBs In-Reply-To: <1163068713.669375.308900@b28g2000cwb.googlegroups.com> References: <1163068713.669375.308900@b28g2000cwb.googlegroups.com> Message-ID: <45531454$0$1130$ba620e4c@news.skynet.be> Sorry I have no direct answer for you, but suspect you should post to the cx_Oracle group. Check the sourceforge project page. It is also conveniently mirrored at news.gmane.org. From stanc at al.com.au Fri Nov 17 02:04:30 2006 From: stanc at al.com.au (Astan Chee) Date: Fri, 17 Nov 2006 18:04:30 +1100 Subject: popen(1-4) as a seperate process In-Reply-To: References: <455D3F18.40902@al.com.au> Message-ID: <455D5EFE.40803@al.com.au> Fredrik Lundh wrote: > Astan Chee wrote: > > >> Im trying to popen (or more specifically os.popen4() ) from wxPython. >> I've read the documentation on popen and it says I can do a popen as a >> seperate process or popen not as a child process >> > > where does it say that? afaik, the whole point of the popen API is to > run an external process and use pipes to communicate with it. > > > > Yes, that is true. But everytime I run a os.popen() it executes as a child process of the current running one. How do I launch as a seperate process? Note that I dont care about whatever happens to the seperate process itself. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Sun Nov 5 08:04:19 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 05 Nov 2006 13:04:19 GMT Subject: finding the list of the matched strings In-Reply-To: <1162731282.327715.49800@f16g2000cwb.googlegroups.com> References: <1162731282.327715.49800@f16g2000cwb.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > Hi, I have a list of strings. And I want to find the subset which > matches a particular regular expression. > > import re > ll = ('a', 'b', 's1', 's2', '3s') > p = re.compile('^s.*') > newList = filter(lambda s: p.match(s), ll) > > I suppose there should be simple function to do this in re module. Is > there any? > > I searched google, but could not find one, may be for keywords were not > perfect. > > Thanks. > Suresh > I think I'm having some network problems. I'll try again. Also the previous "attempt" had a typo (perhaps a freudian slip). ",".join(some_list). By the way, don't name your own objects with the names of built-in types, such as "list" or "str", etc. From bhartesh at gmail.com Thu Nov 2 14:52:57 2006 From: bhartesh at gmail.com (Bhartesh Doshi) Date: Thu, 2 Nov 2006 14:52:57 -0500 Subject: Accessing Javascript variable in python chunk in spyce Message-ID: <9df2a5ae0611021152j468d4884uc5380b2d020acb62@mail.gmail.com> Hi. I am using spyce and coding protions in java script and python chunks. I want to use a variable defined and calculated in java script in a python chunk. Is this possible. Regards, Bhartesh. -------------- next part -------------- An HTML attachment was scrubbed... URL: From haraldarminmassa at gmail.com Sat Nov 4 08:07:28 2006 From: haraldarminmassa at gmail.com (GHUM) Date: 4 Nov 2006 05:07:28 -0800 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: Message-ID: <1162645648.361708.99490@f16g2000cwb.googlegroups.com> robert, > Interprocess communication is tedious and out of questio [...] > I expect to be able to directly push around Python Object-Trees between the 2 (or more) interpreters by doing some careful locking. Please do yourself a favour and have a look at pyro. pyro makes InterComputer and InterProcess Communication a snap. And it allows you to push around Python Objects not only between processes, but computers. Maybe it solves your problem much easier and even more than you want to solve it now by being able to use more then one computer. Harald From larry.bates at websafe.com Sat Nov 4 09:08:15 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 04 Nov 2006 08:08:15 -0600 Subject: how do I pass values between classes? In-Reply-To: <1162592180.494470.257040@h54g2000cwb.googlegroups.com> References: <1162592180.494470.257040@h54g2000cwb.googlegroups.com> Message-ID: <454C9ECF.5020806@websafe.com> kath wrote: > hi everyone......... > > I have a task, I have fragmented the task into subtask. I have planned > to create a class to each subclass and one parent class to handle the > sub tasks. Each subclass are saved in seperate file and all my > subclasses and parent class are placed in the same folder. > > The parent class is subclass of wx.Frame, and subclasses are subclass > of wx.Panel. Each subclass will create a GUI for each task.. > > ok.. here is problem > > When a menu is selected in the parent class, im instantiating the child > class(i.e, Panel), which has textbox and two buttons. first button is > used to select a file, and second one I have planned to, read the file > and pass the values to parent class [B]OR[/B] pass the filepath to > parent to read and do rest of the work. > > How do I do that? > > Please tell me whether I am following a correct method, by fragmenting > task into small task and assigning it to child class and saving it in > a separate file?. > > ok, here is the Parent class > [code] > import wx > import client > """My Parent class""" > class Parent(wx.Frame): > def __init__(self, parent, id, title): > wx.Frame.__init__(self, parent, id, title) > > menu=wx.Menu() > menu.Append(5000, "File") > menu.AppendSeparator() > menu.Append(5001, "Exit") > menubar=wx.MenuBar() > menubar.Append(menu, "File") > self.SetMenuBar(menubar) > self.Bind(wx.EVT_MENU, self.OnFile,id=5000) > self.Bind(wx.EVT_MENU, self.OnExit,id=5001) > > def OnFile(self, event): > self.cl=client.Child(self, -1) > > def OnBrowse(self, event): > dir="" > d=x.FileDialog(self, "Choose an Excel file", self.dirname, "", > "*.xls", wx.OPEN) > if d.ShowModal() == wx.ID_OK: > self.filename=d.GetFilename() > self.dirname=d.GetDirectory() > self.filepath.SetValue(os.path.join(self.dirname, > self.filename)) > > def OnUpload(self, event): > pass > > def OnExit(self, event): > self.Close() > > class MyApp(wx.App): > def OnInit(self): > frame=Parent(None, -1, "Parent window") > frame.Show(True) > self.SetTopWindow(frame) > return True > > if __name__ == '__main__': > app=MyApp(redirect=False) > app.MainLoop() > > [/code] > > and Child class > [code] > import wx, os > > """My Child class""" > > class Child(wx.Panel): > def __init__(self, parent, id): > wx.Panel.__init__(self, parent, id, size=(300,300)) > box=wx.BoxSizer(wx.HORIZONTAL) > label=wx.StaticText(self, -1, "File Path: ") > > self.text=wx.TextCtrl(self, -1) > browse=wx.Button(self, -1,"Browse") > upload=wx.Button(self, -1, "Upload") > self.Bind(wx.EVT_BUTTON, self.OnBrowse, browse) > self.Bind(wx.EVT_BUTTON, self.OnUpload, upload) > box.Add(label) > box.Add(self.text) > box.Add(browse) > > mainbox=wx.BoxSizer(wx.VERTICAL) > mainbox.Add(box) > mainbox.Add(upload) > > self.SetSizer(mainbox) > mainbox.Layout() > def OnBrowse(self, event): > self.dir="" > d=wx.FileDialog(self, "Choose an Excel file", self.dir, "", > "*.xls", wx.OPEN) > if d.ShowModal() == wx.ID_OK: > self.filename=d.GetFilename() > self.dir=d.GetDirectory() > self.text.SetValue(os.path.join(self.dir, self.filename)) > > def OnUpload(self, event): > pass > > class MyApp(wx.App): > def OnInit(self): > frame=wx.Frame(None, -1, "Child window") > panel=Child(frame, -1) > frame.Show(True) > self.SetTopWindow(frame) > return True > > if __name__ == '__main__': > app=MyApp() > app.MainLoop() > [/code] > > thank you, > regards, > kath. > You might consider doing it the same way wx passes things around. When you instantiate the subclass pass the parent class' instance as first argument to __init__ method. That way the subclass can easily pass values back to the parent by using that pointer. -Larry From bearophileHUGS at lycos.com Sun Nov 5 09:53:21 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 5 Nov 2006 06:53:21 -0800 Subject: string to list of numbers conversion In-Reply-To: <1162730071.953080.284980@i42g2000cwa.googlegroups.com> References: <1162730071.953080.284980@i42g2000cwa.googlegroups.com> Message-ID: <1162738401.227476.284950@e3g2000cwe.googlegroups.com> jm.suresh at no.spam.gmail.com wrote: > Hi, > I have a string '((1,2), (3,4))' and I want to convert this into a > python tuple of numbers. But I do not want to use eval() because I do > not want to execute any code in that string and limit it to list of > numbers. > Is there any alternative way? This is a possibile solution, no input errors are taken into account: >>> s = '((1,2), (3,4), (-5,9.2))' >>> from string import maketrans >>> tab = maketrans("(), ", " "*4) >>> s.translate(tab) ' 1 2 3 4 -5 9.2 ' >>> l = s.translate(tab).split() >>> l ['1', '2', '3', '4', '-5', '9.2'] >>> l2 = map(float, l) >>> l2 [1.0, 2.0, 3.0, 4.0, -5.0, 9.1999999999999993] >>> # This is partition(l2, 2) >>> [l2[i:i+2] for i in xrange(0, len(l2), 2)] [[1.0, 2.0], [3.0, 4.0], [-5.0, 9.1999999999999993]] Bye, bearophile From jussij at zeusedit.com Wed Nov 8 22:08:37 2006 From: jussij at zeusedit.com (jussij at zeusedit.com) Date: 8 Nov 2006 19:08:37 -0800 Subject: auto indent References: Message-ID: <1163041717.308959.151840@h54g2000cwb.googlegroups.com> M.N.Smadi wrote: > i have a script that is not indented properly. Is there > a way that i can have it auto indented. FWIW the Zeus for Windows IDE will fold Pyhon code: http://www.zeusedit.com/features.html With the code folded you can then select the folded line and using 'tab'/'shift tab' Zeus will indent/re-indent all the lines contained in the fold. It is not an automatic re-indenting solution but it might be better than nothing ;) Jussi Jumppanen Author: Zeus for Windows IDE From george.sakkis at gmail.com Thu Nov 23 15:21:52 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 23 Nov 2006 12:21:52 -0800 Subject: Trying to understand Python objects References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> <4565f8f7$0$8460$426a74cc@news.free.fr> Message-ID: <1164313312.818503.168790@j72g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > AFAIK, everything you do with old-style classes can be done with new-style ones. The only thing I occasionally (or rather rarely) miss about old-style classes is instance-specific special methods: >>> class C: ... def __init__(self,x): ... self.__getitem__ = lambda i: i*x ... >>> c=C(2) >>> c[3] 6 >>> class N(object): ... def __init__(self,x): ... self.__getitem__ = lambda i: i*x ... >>> n=N(2) >>> n[3] Traceback (most recent call last): File "", line 1, in ? TypeError: unindexable object Of course this example can be rewritten to work for new style classes; a trickier would be to bind the instance attribute conditionally; here's a silly example: >>> class C: ... def __init__(self,x): ... if random.random() > 0.5: ... self.__getitem__ = lambda i: i*x I'm not sure if this is a conscious choice or a technical limitation of how new-style classes work internally, but I've had a use for it at least once. George From haraldarminmassa at gmail.com Sat Nov 4 08:00:15 2006 From: haraldarminmassa at gmail.com (GHUM) Date: 4 Nov 2006 05:00:15 -0800 Subject: codecs - where are those on windows? In-Reply-To: References: <1162202194.839564.30470@b28g2000cwb.googlegroups.com> <45461B1B.6070101@redlinepy.com> Message-ID: <1162645215.005872.35230@i42g2000cwa.googlegroups.com> Fredrik Lundh schrieb: > > If your installation directory is C:\Python25, then look in > > C:\Python25\lib\encodings > > that's only the glue code. the actual data sets are provided by a bunch > of built-in modules: > >>> import sys > >>> sys.builtin_module_names > ('__builtin__', '__main__', '_ast', '_bisect', '_codecs', > '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', > '_codecs_kr', '_codecs_tw', ... So, it should be possible to do a custom build of python24.dll / python25.dll without some of those codecs, resulting in a smaller python24.dll ? It will be some time untill my apps must support Chinese and Japanese... Harald From sturlamolden at yahoo.no Wed Nov 8 13:55:47 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 8 Nov 2006 10:55:47 -0800 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <1163007675.919803.158010@m7g2000cwm.googlegroups.com> References: <1163007675.919803.158010@m7g2000cwm.googlegroups.com> Message-ID: <1163012147.305772.191560@i42g2000cwa.googlegroups.com> sturlamolden wrote: > 3. One often uses cluster architectures (e.g. Beowulf) instead of SMPs > for scientific computing. MPI works on SMP and clusters. Threads only > work on SMPs. Following up on my previous post, there is a simple Python MPI wrapper that can be used to exploit multiple processors for scientific computing. It only works for Numeric, but an adaptaion to NumPy should be easy (there is only one small C file in the source): http://datamining.anu.edu.au/~ole/pypar/ If you are using Windows, you can get a free implementation of MPI here: http://www-unix.mcs.anl.gov/mpi/mpich1/mpich-nt/ From fredrik at pythonware.com Fri Nov 3 02:45:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 03 Nov 2006 08:45:21 +0100 Subject: __doc__ in compiled script In-Reply-To: <7.0.1.0.0.20061102215407.05c151e0@yahoo.com.ar> References: <7.0.1.0.0.20061102215407.05c151e0@yahoo.com.ar> Message-ID: Gabriel Genellina wrote: >> >>> co.co_consts[list(co.co_names).index("__doc__")] >> 'This is a docstring' > > Good! I'll buy this one :) thanks! however, there's no 1:1 mapping between names and constants; if you want code that works by accident, you might as well use co_consts[0]. From claird at lairds.us Wed Nov 8 08:39:06 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 8 Nov 2006 13:39:06 +0000 Subject: Python deployment options. References: <1162982262.010438.99260@f16g2000cwb.googlegroups.com> <1162985073.163257.110180@m73g2000cwd.googlegroups.com> <1162986129.233443.268730@h54g2000cwb.googlegroups.com> <1162990156.204577.198720@h48g2000cwc.googlegroups.com> Message-ID: In article <1162990156.204577.198720 at h48g2000cwc.googlegroups.com>, Richard Charts wrote: . . . >Well on a Win machine, probably. >Almost every Linux machine you come across will have (most likely a >fairly recent build of) python. For Macs, I'm not so sure but it's >probably closer to Linux than Win. > Recent releases of Mac OS build in Python. From siona at chiark.greenend.org.uk Mon Nov 13 10:56:28 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 13 Nov 2006 15:56:28 +0000 (GMT) Subject: httplib.InvalidURL: nonnumeric port: For characters in the proxypassword in URL References: <1163408210.915911.327430@k70g2000cwa.googlegroups.com> <1163419232.632721.192360@i42g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: >>>> urllib.quote > >>>> urllib2.quote > >>> urllib.quote >>> urllib2.quote Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'quote' >>> sys.version '2.4.1 (#2, May 5 2005, 11:32:06) \n[GCC 3.3.5 (Debian 1:3.3.5-12)]' -- \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" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From sybrenUSE at YOURthirdtower.com.imagination Thu Nov 2 06:35:06 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 2 Nov 2006 12:35:06 +0100 Subject: other ways to check for ? References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> <4549cf05$0$9363$426a74cc@news.free.fr> Message-ID: Christophe enlightened us with: > I don't think it's a good idea because when you place a try catch > block around a function call, you'll catch any exception thrown by > the function itself and not only the "cannot be called" exception. That depends on the exception you're catching, doesn't it? Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From jkn_gg at nicorp.f9.co.uk Tue Nov 21 06:50:30 2006 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 21 Nov 2006 03:50:30 -0800 Subject: Misleading IOerror when opening a non-existent file for append? In-Reply-To: References: <1164037095.148334.157670@e3g2000cwe.googlegroups.com> <1164037676.537263.53480@f16g2000cwb.googlegroups.com> Message-ID: <1164109830.629768.51130@k70g2000cwa.googlegroups.com> Hi there Thanks for the comments. I see that I actually confused myself a bit with my posting. It's been a while and I mistook the use of '/' as a platform-independent directory delimiter with the use of '\\'. I also thought that I was seeing something similar on Windows and Linux. This may not be the case ;-o. So, to try again. It looks as it the attempt to open a non-existent file (for instance, because the parent folder does not exist) gives an odd error on Linux but not on Windows. On Windows: > >>> f = file(r'c:\does-not-exist\DoesNotExist.txt','a') > > Traceback (most recent call last): > File "", line 1, in > f = file(r'c:\does-not-exist\DoesNotExist.txt','a') > IOError: [Errno 2] No such file or directory: 'c:\\does-not-exist > \\DoesNotExist.txt' > >>> (replacing the '\' with '/' gives the same message, which is what I was trying to convey) On Linux, you get the 'Bad mode' error. Strange?! Jon N From bignose+hates-spam at benfinney.id.au Mon Nov 13 23:56:15 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 14 Nov 2006 15:56:15 +1100 Subject: Test-driven development of random algorithms References: Message-ID: <87fycmhbio.fsf@benfinney.id.au> Robert Kern writes: > Steven D'Aprano wrote: > > Does anyone have generic advice for the testing and development of > > this sort of function? > > "Design for Testability". In library code, never call the functions > in the random module. Always take as an argument a random.Random > instance. When testing, you can seed your own Random instance and > all of your numbers will be the same for every test run. Even better, you can pass a stub Random instance (that fakes it) or a mock Random instance (that fakes it, and allows subsequent assertion that the client code used it as expected). This way, you can ensure that your fake Random actually gives a sequence of numbers designed to quickly cover the extremes and corner cases, as well as some normal cases. This applies to any externality (databases, file systems, input devices): in your unit tests, dont pass the real externality. Pass a convincing fake that will behave entirely predictably, but will nevertheless exercise the functionality needed for the unit tests. This is one of the main differences between unit tests and other kinds. With unit tests, you want each test to exercise as narrow a set of the client behaviour as feasible. This means eliminating anything else as a possible source of problems. With other tests -- stress tests, acceptance tests, and so on -- you want to exercise the entire application stack, or some significant chunk of it. -- \ "It is the mark of an educated mind to be able to entertain a | `\ thought without accepting it." -- Aristotle | _o__) | Ben Finney From bugracakir at gmail.com Thu Nov 16 08:20:01 2006 From: bugracakir at gmail.com (Bugra Cakir) Date: Thu, 16 Nov 2006 15:20:01 +0200 Subject: Heap Memory Message-ID: <5a00f6240611160520r1056e76er84acf2ac751507d0@mail.gmail.com> Hi my name is Bugra Cakir, I have a question. How can we increase heap memory or total memory Python interpreter will use in order to avoid memory problems ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From phil at riverbankcomputing.co.uk Sat Nov 18 13:07:33 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Sat, 18 Nov 2006 18:07:33 +0000 Subject: please help me choose a proper gui library. In-Reply-To: References: Message-ID: <200611181807.33571.phil@riverbankcomputing.co.uk> On Saturday 18 November 2006 5:44 pm, krishnakant Mane wrote: > hello all. > after finishing a project in record time using python we have taken up > one more project. > this time however, we need to do a gui based project which will run > on windows xp and 2000. > now My question is which gui toolkit should I choose? > I had initially raised some doubt about accessibility (which is very > important for me ), and with the answers and all the pointers given, I > know that wxpython is quite out of question. > now my next choice is PyQT. > can some one give me information on the following points? > 1. do I first need to install the pure c++ based QT library both on > the developer machine and the client's user machine? You have to install Qt first. You only need to install the run-time elements (ie. the DLLs) on the client's machine. Unless your application is licensed under the GPL (and you are using the GPL version of Qt and PyQt) then there are components of Qt that you must not install on the client's machine. > 2. I need an executable binary installer for windows xp. is it > available for python24? I searched but found one for python25. else > kindly guide me what should I do to install the source. I read the > documentation but did not get the clear idea whether I must have qt > installed first or not. if yes are there binary installers of PYQT > which can also install qt? The only binary installer provided is for the GPL version of PyQt. Qt has separate installers. It's easy enough to use something like NSIS to create your own installer for your application that includes everything that it needs. > 3. if I need to upgrate to python25, should it be considered safe? PyQt fully supports Python 2.5. > 4. I don't want to use the qt IDE and this point is nothing to do > with qt, I need a good windows based python editor. Google for the different ones and try them out. > 5. if I am supposed to also distrubute qt with PYQT, how do I plan > the deployment of my ready software? In addition to your application you need to distribute the Qt DLLs (and plugins if you use them), the corresponding PyQt .pyd files and sip.pyd. If you are using the GPL version of Qt then you may also need to consider the MinGW DLLs. Finally you need to consider if you need to distribute Python itself. You might like to look at tools like PyInstaller for creating single executables. Phil From bignose+hates-spam at benfinney.id.au Thu Nov 2 00:55:31 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 02 Nov 2006 16:55:31 +1100 Subject: can I import the module twice (under differnet names) References: Message-ID: <87bqnq4cks.fsf@benfinney.id.au> alf writes: > wonder if in the python I could treat modules imorts like classes > instances. It means I could import it twice or more times under > different names. No need to import more than once. The 'import' statement binds a module object to the specified name, and you can bind as many names as you like to the same object. >>> import sys >>> foo = sys >>> bar = sys >>> print sys.maxint 2147483647 >>> print foo.maxint 2147483647 >>> print bar.maxint 2147483647 -- \ "Laugh and the world laughs with you; snore and you sleep | `\ alone." -- Anonymous | _o__) | Ben Finney From Rony.Flatscher at wu-wien.ac.at Sat Nov 25 10:06:08 2006 From: Rony.Flatscher at wu-wien.ac.at (rony) Date: Sat, 25 Nov 2006 16:06:08 +0100 Subject: Ruby/Python/REXX as a MUCK scripting language In-Reply-To: <2006112418112116807-zobeid@techiecom> References: <2006112418112116807-zobeid@techiecom> Message-ID: <45685BE0.10209@wu-wien.ac.at> Hi Tony, Tony Belding wrote: > I'm interested in using an off-the-shelf interpreted language as a > user-accessible scripting language for a MUCK. I'm just not sure if I > can find one that does everything I need. The MUCK must be able to call > the interpreter and execute scripts with it, but the interpreter must > also be able to call functions in the MUCK code. And then there's the > security issue that really worries me. . . I have to be able to limit > what the interpreter can execute. I can't have my users running scripts > that access the console, access the filesystem or sockets directly, or > call libraries or other binaries outside the MUCK. > > Is this practical? I'm thinking of Ruby or Python for this, if they can > meet the requirements. > > I might even consider REXX. . . I remember ARexx from my Amiga days, > and how great it was for string manipulation and application scripting. > However. . . My immediate target platform, Mac OS X, comes with Ruby > and Python but not REXX, so that's a disadvantage. > > My final option would be to create my own language interpeter where I > have control over everything that happens. That is what MUCKs have > always done in the past. But the result was always quirky, limited > languages like MUF (Multi-User Forth) which really turn off a lot of > coders. Furthermore, I've never created a language before, and it would > be a lot of extra work for me. Well, a few remarks here ad the REXX options that would be available to you: - REXX (there was its 25th anniversary celebrated in 2004) has an object-oriented successor that still can execute plain REXX code, but is realized as an object-oriented language: Object REXX. It got originally developed by IBM, after their big customers indicated that they would be interested in it. In 1997 Object REXX became part of OS/2 Warp 4. IBM sold Object REXX for AIX and Windows. - In 2004 after negotiations took place with the non-profit Rexx Language Association (RexxLA, http://www.RexxLA.org), IBM handed the source code of Object REXX over to the RexxLA which created a free and open source version and distributed it in April 2005 for the first time as Open Object Rexx (ooRexx) 3.0, cf. ). - The ooRexx source-code is hosted on Sourceforge and uses the Common Public License (CPL) 1.0 (cf. ). This means that you can freely use the code, edit it your way and make it even part of your own (even commercial) product. - This week a new drop of ooRexx, version 3.1.1, has been released, with binaries built for AIX (first time that an official ooRexx binary got build for it!), Linux, MacOSX (first time that an official ooRexx binyry got build for it PPC, Intel), Solaris (Intel, Sparc), and Windows. [Additional binaries for additional environments can be built using the autoconf tools.] So ooRexx has been made available for your main target platform for your MUCK application. - Ad your needs w.r.t. calling functions of your MUCK applicaiton: yes, that is possible (and not difficult at all). - Ad your needs w.r.t. security needs of your MUCK application: yes, that is possible (and not difficult at all): Because of the history of ooRexx (it was a commercial product to be deployed at large sites, security was a paramount issue), there is a Security Manager built into ooRexx. The ooRexx security architecture is quite interesting, easy to use, very flexible as it allows you to create as many differenct security policy rules as you may wish. The ooRexx security manager will monitor all potential insecure actions from REXX and ooRexx programs (like accessing the environment, accessing streams, accessing functions etc.) and inform the policy program about such intended, possibly secure-threatening operations. The policy program then is able to decide to let the action through, to execute a secure operation instead without the supervised REXX or ooRexx program noticing this (!), or stop the execution of the supervised program alltogether. If you are interested in this and need ideas, help for your MUCK needs, then please post, such that people over here (ie. the ) can help you out. - Ad ooRexx in general: it is an easy to learn and easy to use (follows still the original REXX philosophy to be a "human centric" language!!), fully object-oriented language (influenced by Smalltalk). There is a small, tutorial-like paper (written for this year's European Conference of Object-Oriented Programming, ECOOP, workshop named "Revival of Dynamic Languages (RDL) ", which really gives a brief overview of the history and the (interesting) features of the ooRexx langauge, entitled "Resurrecting REXX, Introducing Object Rexx", to enable reflection and discussion of the language and its interesting concepts, cf.: . At the end of the paper there are a few, but actually quite impressive nutshell examples, demonstrating the ease and power of ooRexx in different environments. - Ad prospects of ooRexx: ooRexx is actively being developed and enhanced. The RexxLA has been organizing a yearly "International Rexx Symposium", the 2007 symposium to probably take place in Tampa, Florida, USA, from April 29th, 2007, through May 3rd, 2007. Maybe you or your partners may want to stop by there (the conferences are rather personal, you get to meet everyone in person who has been actively developing ooRexx and ooRexx applications)? 8-)) Again, if you have any questions, please post them. Regards, ---rony P.S.: I have been using ooRexx in classes introducing MIS students to oo-concepts and programming, such that "enduser-programmer" kind of people can successfully deploy their acquired skills to automate/remote-control/script Windows, Windows applications, but also Java and Java applications and applications like OpenOffice/StarOffice possessing Java interfaces. As a matter of fact, such students become able to create scripts to drive e.g. OpenOffice which run unchanged e.g. on MacOS, Linux and Windows, which is actually very cost-effective and impressive, if one thinks about it! From johnjsal at NOSPAMgmail.com Thu Nov 9 10:29:40 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 09 Nov 2006 10:29:40 -0500 Subject: is this the right way to do subclasses? In-Reply-To: <45525b3e$0$32029$426a34cc@news.free.fr> References: <45522074$0$17101$c3e8da3@news.astraweb.com> <45524f40$0$32365$c3e8da3@news.astraweb.com> <45525b3e$0$32029$426a34cc@news.free.fr> Message-ID: <4553488e$0$12978$c3e8da3@news.astraweb.com> Bruno Desthuilliers wrote: > John Salerno a ?crit : >> Peter Otten wrote: >> >>> You may need a no-op implementation of fix_attributes() in the Character >>> class. >> >> >> What does that mean? Is that in case I use Character directly to >> create an object? > > Most propbably it can be useful for other character classes that don't > need too fix attributes. Ah, I get it! From johnjsal at gmail.com Thu Nov 2 11:51:39 2006 From: johnjsal at gmail.com (JohnJSal) Date: 2 Nov 2006 08:51:39 -0800 Subject: creating new objects with references to them In-Reply-To: <1162480549.786082.290980@b28g2000cwb.googlegroups.com> References: <1162480549.786082.290980@b28g2000cwb.googlegroups.com> Message-ID: <1162486298.863881.261790@h54g2000cwb.googlegroups.com> JohnJSal wrote: > Hope that makes sense. It seems like such a common task. Ok, I'm thinking about the suggestion to make a list, but I'm still confused. Even with a list, how do I access each instance. Would I have to do it by index? I assume I'd do something like this: self.records = [] # list for storing instances Then when "New Record" is clicked: def OnNewRecord(self, event): self.records.append(Researchers()) But now what? There is still no reference to that instance? The only thing I can think of is that each record will be a tab in a wxPython notebook control, and each tab can be referenced by index. So whichever tab I'm on, I can use that index to get that particular instance in the list. But this solution seems too tied to my particular implementation. How would you normally access these instances in the list? Let's say there are three objects in the list. Someone fills out the text fields for the second one and clicks "Save". I know how to read all the information in the fields, but how do I then associate it with that second instance? (Or I wonder if I really even need to, since upon saving, the information gets stored in the database immediately. Maybe I don't even need a Researcher class at all.) From shansen at advpubtech.com Wed Nov 22 23:40:12 2006 From: shansen at advpubtech.com (Stephen Hansen) Date: Wed, 22 Nov 2006 20:40:12 -0800 Subject: The Python Papers Edition One In-Reply-To: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> Message-ID: <7a9c25c20611222040q139ad3fera14a7afba6f60343@mail.gmail.com> > 3.) Can I have an HTML version? > A) No, we like it pretty. The interesting thing is, there's nothing in your layout or format that you can't do with some nice standards-compliant HTML and CSS. It could look identical as HTML-- and be significantly more "reachable" by people, easier for them to use and read, link to, and so on and so forth. Plus you could stick some Google adwords ads on it :) But, really... if you're eventually wanting this to be a printed/published/mailed sort of thing, I can understand why you'd want to do it as a PDF... but you will be limiting your audience in the meantime. A lot of people just find it too tedious and difficult, and if your goal is to reach people and communicate.... Why not do both? Might take a bit more work-- but the layout you have isn't that hard to do in HTML, and there's gotta be a way to html2pdf... I've never wanted to, but there has to be. =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From john106henry at hotmail.com Fri Nov 17 15:01:01 2006 From: john106henry at hotmail.com (John Henry) Date: 17 Nov 2006 12:01:01 -0800 Subject: remove a list from a list In-Reply-To: References: <455E0046.1090005@tim.thechases.com> <455E0A20.9000509@tim.thechases.com> Message-ID: <1163793661.856365.202930@b28g2000cwb.googlegroups.com> The curve ball is the case insensitivity otherwise it's a straightforward set operation. I wonder if it's possible to sub-class set and make the item comparision case insensitive. Anybody knows how to do that? Tim Chase wrote: > > Yeah, I ended up doing a similar kind of loop. That is pretty messy. > > > > Is there any other way? > > I've already provided 2 (or 3 depending on how one counts) > solutions, each of which solve an interpretation of your original > problem, neither of which involve more than 3 lines of fairly > clean code. Perhaps a little more context regarding what you > *want* to do would help. However, I suspect that answer is > "there is no *cleaner* way to do it". > > Unless you're modifying an existing list that is referenced > elsewhere, the reassignment (l = [x for x in l ...]) solution > should work just fine. Thus, unless you have a situation akin to: > > g = l > l = [x for x in l if x.lower() not in s] > assert(thing_from_s not in g) > > then just reassign "l". If not, use the loop. It's that easy > and clean. Don't try to opaquify it by collapsing it further. > Perhaps, if your loop is messy, use my clean loop suggestion. > > -tkc From sjmachin at lexicon.net Wed Nov 1 21:28:46 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Nov 2006 18:28:46 -0800 Subject: CSV module, DictReader problem (bug?) In-Reply-To: References: <1162415232.190913.163240@m73g2000cwd.googlegroups.com> Message-ID: <1162434526.601605.315560@k70g2000cwa.googlegroups.com> Tom Plunket wrote: > John Machin wrote: > > > If you were to write 'c:\temp\book1.csv', it would blow up ... because > > \t -> tab and \b -> backspace. Get into the habit of *always* using raw > > strings r'C:\Temp\Book1.csv' for Windows file names (and re patterns). > > You could use double backslashing 'C:\\Temp\\Book1.csv' but it's > > uglier. > > ...alternatively you can just use 'unix slashes', e.g. > 'c:/temp/book1.csv', since those work just fine 'cause the Windows > APIs deal with them properly. Not all APIs do the right thing. If you fire up the cmd.exe shell and feed it slashes as path separators, it barfs. Example: C:\junk>dir c:/junk/*.bar Invalid switch - "junk". Hence the advice to use rawstrings with backslashes -- they work under all circumstances. From svein at seldal dot com Thu Nov 16 18:22:20 2006 From: svein at seldal dot com (Svein Seldal) Date: Fri, 17 Nov 2006 00:22:20 +0100 Subject: Multithreaded C API Python questions In-Reply-To: References: <7vCdnSqE260grc7YRVnzvQ@telenor.com> Message-ID: robert wrote: > Forget all the low level PyGIL... functions.' Quite the contrary, I would say! From the Py C API doc, I interpret the PyGIL... functions to be higher leveled than eg. PyEval_SaveThread(). I've checked into the source of python to find out what's really going on, and I've learnt a couple of interesting facts. The PyGIL... are helper functions build over the PyEval... functions, not the other way around. A real beauty about the PyGILState_Ensure() is the fact that if it's called from a thread that is (yet) unknown to python, it will actually create the thread state object for you (with PyThreadState_New) and acquire the lock. Hence, I dont have to worry about the process of swapping thread states with PyEval_xxxThread() functions. I ONLY need to use PyGILState_Ensure() prior to any py-ops. From my previous post, I asked about the difference between PyEval_ReleaseLock() and PyEval_ReleaseThread() and I've found one major difference. Both release the GIL as the docs states, but the PyEval_ReleaseThread() saves the current thread state as well. When I used PyEval_ReleaseLock() this didnt happen, preventing proper saving of the current thread, causing py crash when control were handed back to this thread. By using: PyEval_InitThreads(); py_ops(); PyThreadState *pts = PyGILState_GetThisThreadState(); PyEval_ReleaseThread(pts); And for each py-op later on (from arbitrary thread): PyGILState_STATE gstate; gstate = PyGILState_Ensure(); py_ops(); PyGILState_Release(gstate); Then you're home free. Everything related to threading is handled by Py/API itself. > Probably you just do a PyRun_xxxx in main thread and then everything > else in Python, and expose C-parts for the thread-loop to Python as > function (in other_py_inits) - where in the c-function you probably have > the usual Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS bracket during > time consuming/system/reenter-endangered message stuff. The app i'm building is a plugin to a server system, and I cant control nor remove any threads that the server uses. I am given one main thread to run python forever, and messages that are to be delivered into python are called from another. I could do it like you propose: The data coming from my server will arrive into a c-function called by a server thread. The c-part of the thread-loop would then be run as another thread (started from python). Its fully feasible, yet the challenge is to make proper data sync-ing between these two threads. Well, I think I've achieved what I wanted. Python seems apparently stable, and reading from the python sources, I cant see any immediate reasons why it shouldn't. Thanks for letting me closer to a working solution! Regads, Svein From deets at nospam.web.de Thu Nov 9 17:56:20 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 09 Nov 2006 23:56:20 +0100 Subject: Simple question to split In-Reply-To: <4rhpvgFrneqhU2@mid.uni-berlin.de> References: <4rhov8Frk45nU1@mid.uni-berlin.de> <4rhpvgFrneqhU2@mid.uni-berlin.de> Message-ID: <4rhq0jFrneqhU3@mid.uni-berlin.de> Diez B. Roggisch schrieb: > Matthias Winterland schrieb: >> Hi, >> >> I have a simple question. When I read in a string like: >> a='1,2,3,4,5 6 7,3,4', can I get the list l=[1,2,3,4,5,6,7,3,4] with a >> single split-call? > > Nope. But you could replace the commas with spaces, and then split. Or use re.split.... Diez From spe.stani.be at gmail.com Wed Nov 29 09:49:57 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 29 Nov 2006 06:49:57 -0800 Subject: Stani's Python Editor is looking for a new webhost Message-ID: <1164811797.717948.147530@16g2000cwy.googlegroups.com> SPE was hosted for a long while by Zettai. I'd like to thank them again for their wonderful service. Unfortunately they will go out of business. So SPE is looking for a new webhost. These are the requirements: - python framework (Zope/Plone, django, turbogears, ...) - I have the freedom to use this website also for other projects besides SPE (such as sdxf (open source dxf library for python), my own portfolio, ... - I am allowed to place ads on the site (eg Google Adsense) These are some optional features which would be nice: - root access - debian or ubuntu based - domain registration for stani.be In return a small banner of the hosting (or sponsering) will be placed on the SPE site. You can reach me by email: spe.stani.be at gmail. The SPE website gets around 1500 visitors a day. If there are some zope/plone, django, turbogears, ... enthousiasts or companies want to help building the site, please contact me as well. Every offer will be appreciated, but of course I can only choose one. In order to continue the development of SPE, it needs a hosting provider. Thanks for any suggestions, Stani From chris at kateandchris.net Tue Nov 7 16:36:38 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Tue, 7 Nov 2006 16:36:38 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 7) In-Reply-To: <4550f7b9$0$14445$c3e8da3@news.astraweb.com> References: <4550f7b9$0$14445$c3e8da3@news.astraweb.com> Message-ID: <20061107213638.GB6506@kateandchris.net> On Tue, Nov 07, 2006 at 04:15:39PM -0500, John Salerno wrote: > Cameron Laird wrote: > > > Fredrik Lundh collects pyidioms: > > http://effbot.org/zone/python-lists.htm > > Not working? perhaps http://effbot.org/zone/python-list.htm ? From paul at boddie.org.uk Sat Nov 25 10:43:27 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 25 Nov 2006 07:43:27 -0800 Subject: The Python Papers Edition One References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <7xodqyn5kd.fsf@ruckus.brouhaha.com> <1164323350.988946.209350@l12g2000cwl.googlegroups.com> <16651e80611242126u55685813u7d77f299c738963e@mail.gmail.com> Message-ID: <1164469407.937514.190400@l39g2000cwd.googlegroups.com> Jerry Hill wrote: > > MontyLingua is GPL software and thus has its own licensing issues for > > commercial software. MontyLingua might appear to be GPL-licensed, but then the author puts some kind of non-commercial clause on top, either thinking that's what the GPL is all about (out of confusion, perhaps), or believing that he can limit the rights of the those who license his code. The effect is that the code is not actually GPL-licensed at all, given the stated conditions on distribution. See here for more discussion: http://lists.debian.org/debian-legal/2004/08/msg00622.html Paul P.S. This obsession in academia for non-commercial licences is quite a destructive force: everyone "protects" their own work yet steers clear of other people's work, redoing what they need themselves, mostly because they've got an eye on "monetizing" that work later on. Consequently, the cult of the almighty dollar gets more out of it than scientific progress does. From timr at probo.com Tue Nov 28 02:39:00 2006 From: timr at probo.com (Tim Roberts) Date: Tue, 28 Nov 2006 07:39:00 GMT Subject: splitting a long string into a list References: <1164692082.272978.66720@14g2000cws.googlegroups.com> Message-ID: <2qpnm2984p6q76vd9p1jhj65if9ri5eva1@4ax.com> "ronrsr" wrote: >I have a single long string - I'd like to split it into a list of >unique keywords. Sadly, the database wasn't designed to do this, so I >must do this in Python - I'm having some trouble using the .split() >function, it doesn't seem to do what I want it to - any ideas? > >thanks very much for your help. > >r-sr- > > >longstring = 'Agricultural subsidies; Foreign aidAgriculture; >Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, >Childhood Development, Birth Defects; Toxic ChemicalsAntibiotics, >AnimalsAgricultural Subsidies, Global TradeAgricultural >SubsidiesBiodiversityCitizen ActivismCommunity... What do you want out of this? It looks like there are several levels crammed together here. At first blush, it looks like topics separated by "; ", so this should get you started: topics = longstring.split("; ") -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at holdenweb.com Fri Nov 10 03:00:16 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 10 Nov 2006 02:00:16 -0600 Subject: how is python not the same as java? In-Reply-To: <87k624j622.fsf@benfinney.id.au> References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> <87k624j622.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Steve Holden writes: > >> Java is horrible, Oython is not. > > Is that the predecessor to Python, the one that could only be > expressed in vowel noises? > You're taking the oiss, right? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From eric_brunel at despammed.com Fri Nov 10 03:11:46 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 10 Nov 2006 09:11:46 +0100 Subject: How to choose the right GUI toolkit ? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163112691.552233.130650@e3g2000cwe.googlegroups.com> Message-ID: On Thu, 09 Nov 2006 23:51:31 +0100, Dan Lenski wrote: > One other thing I'm wondering: how exactly does Tkinter work? Is the > whole Tk toolkit bound up as library of low-level C code, or does > Tkinter sit on top of a Tcl interpreter? The latter: there is a tiny C layer allowing Python to call an embedded tcl interpreter. > If the latter, that might explain why it is frustratingly slow on > Cygwin... since Cygwin is not very good at starting up new processes in > a timely manner. There is no other process involved: the interpreter is embedded, just as a Python interpreter can be embedded in a C application. If you want to work with Tkinter on Windows, you'd better avoid Cygwin. Python with Tkinter works just fine on Windows, just as it works on any other platform, and is fully portable, just as tcl/tk is. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From jfigueiras at sapo.pt Wed Nov 22 07:40:48 2006 From: jfigueiras at sapo.pt (jfigueiras at sapo.pt) Date: Wed, 22 Nov 2006 12:40:48 +0000 Subject: Capture file descriptors while running an external program Message-ID: <1164199248.3lj9jkctog8w@w3.mail.sapo.pt> Hi all! I have a problem with the module subprocess! The problem is that the external software that I am running under subprocess.Popen opens stdin, stdout, stderr, and other file descriptors to write and read in the hard drive. I know how to capture stdin, stdout and stderr, what I cannot do is to capture the other file-descriptors. Is there any way to wrap those non-standard file descriptors and make them write and read from a specific object that I define? I know that I can use tmp files to do that, but i would like something running without tmp files. Regards... Joao ___________________________________________________________________ O SAPO j? est? livre de v?rus com a Panda Software, fique voc? tamb?m! Clique em: http://antivirus.sapo.pt From steve at holdenweb.com Fri Nov 3 22:50:11 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 04 Nov 2006 03:50:11 +0000 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> Message-ID: robert wrote: > Daniel Dittmar wrote: > >>robert wrote: [...] > >>>garbage is collected earliest, when the refcount went to 0. If it ever >>>went to 0, no one will ever use such object again. Thus GC should not >>>be different at all. >> >>Since Python 2.?, there's a mark-and-sweep garbage collection in >>addition to the reference counting scheme. This was put into Python to >>be able to reclaim object cycles. > > > still that only walks on objects which have already zero refcount. Cannot imagine any additional problems with the GIL. > If I understand you correctly, then you are suffering a misapprehension. Any object whose reference count goes to zero will immediately be reclaimed. The mark-sweep garbage collector is used to detect objects that are taking part in cycles - sets of objects that only refer to each other without being bound to a name in any current namespace or to any container object bound to such a name. In other words, it detects (and reclaims) objects with non-zero reference counts which nevertheless can be reclaimed without ill effect on the program. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From hg at nospam.com Wed Nov 22 13:53:19 2006 From: hg at nospam.com (hg) Date: Wed, 22 Nov 2006 12:53:19 -0600 Subject: utf - string translation In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > hg wrote: > >> We noticed that len('?') != len('a') > > sounds odd. > >>>> len('?') == len('a') > True > > are you perhaps using an UTF-8 editor? > > to keep your sanity, no matter what editor you're using, I recommend > adding a coding directive to the source file, and using *only* Unicode > string literals for non-ASCII text. > > or in other words, put this at the top of your file (where "utf-8" is > whatever your editor/system is using): > > # -*- coding: utf-8 -*- > > and use > > u'' > > for all non-ASCII literals. > > > Hi, The problem is that: # -*- coding: utf-8 -*- import string print len('a') print len('?') returns 1 then 2 and string.maketrans(str1, str2) requires that len(str1) == len(str2) hg From st at tobiah.org Fri Nov 3 17:01:35 2006 From: st at tobiah.org (tobiah) Date: Fri, 03 Nov 2006 14:01:35 -0800 Subject: WSDL? In-Reply-To: <1162590557.043667.20130@m73g2000cwd.googlegroups.com> References: <454ba334$0$12110$88260bb3@free.teranews.com> <1162590557.043667.20130@m73g2000cwd.googlegroups.com> Message-ID: <454baf57$0$12123$88260bb3@free.teranews.com> I recently wrote a SOAP client(?) to read what the guy from the other company called a WSDL, which was just a URL that served an XML API description. Is that the same as XMLRPC (I ask because you mention SOAP). Thanks, Toby WakeBdr wrote: > XMLRPC and SOAP are the two I'm working with right now. > > > tobiah wrote: >> Is WSDL the right answer for in house communication >> between programs written in different languages, or >> is it more for publishing interfaces for use by parties >> outside your own company? >> >> What else is available for sharing complex structures >> with processes running programs that were written in >> other languages? >> >> Thanks, >> >> Toby >> >> -- >> Posted via a free Usenet account from http://www.teranews.com > -- Posted via a free Usenet account from http://www.teranews.com From XX.XmcX at XX.XmclaveauX.com Wed Nov 1 00:30:14 2006 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Wed, 01 Nov 2006 06:30:14 +0100 Subject: Integrating Python with Fortran References: <1162329971.939178.290250@m7g2000cwm.googlegroups.com> Message-ID: Hi! in afternoon: http://calcul.math.cnrs.fr/article.php3?id_article=150 -- @-salutations Michel Claveau From antroy at gmail.com Fri Nov 10 06:01:40 2006 From: antroy at gmail.com (Ant) Date: 10 Nov 2006 03:01:40 -0800 Subject: Newb: installing Jython on Windows XP ... In-Reply-To: References: <1163095323.668867.58320@i42g2000cwa.googlegroups.com> Message-ID: <1163156500.758696.258390@m7g2000cwm.googlegroups.com> On 10 Nov, 10:29, Marcus Bajohr wrote: > donkeyboy wrote: > > All, > > > I'm having issues installing Jython on Windows XP. I've looked on the ... > > Any help would be of great use!!! > Try it from cmd, not from the cygwin shell. > The environments differ ! Looking at the command prompt, he's not in the cygwin shell. I think that there's a bug in the latest jre from sun. I installed the 1.5.0_09 update a few days ago, and I can't get any apps to run with it (including irritatingly the Java Control Panel application so I can't change the default back easily...) The problems are NoClassDefFoundError's as well, so I wonder if the class loading is broken in that release... Anyway the solution seems to be to use an earlier jre explicitly: "c:\Program Files\Java\jdk1.5.0_06\bin\java.exe" jython-21 1.5.0_06 seems to work fine for me. HTH From stefan.behnel-n05pAM at web.de Wed Nov 22 09:32:51 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 22 Nov 2006 15:32:51 +0100 Subject: XML Validation in Python using XSV In-Reply-To: <1164202262.974495.289490@f16g2000cwb.googlegroups.com> References: <1164200431.878328.175100@f16g2000cwb.googlegroups.com> <45644E9A.3030209@web.de> <1164202262.974495.289490@f16g2000cwb.googlegroups.com> Message-ID: <45645F93.7050907@web.de> > bmichel at gmail.com wrote: > Stefan Behnel wrote: >> BTW: any reason you need to use XSV? There are some other libraries out there >> that can validate XML based on XML Schema and RelaxNG, e.g. lxml. They are >> much more powerful than XSV. > > No particular reason for XSV > I just want to validate XML files against an XML schema through Python. > If you can suggest any other package for debian, I'll be glad to try > it. Well, as I said: http://packages.debian.org/unstable/python/python-lxml http://codespeak.net/lxml/ Just try "apg-get install python-lxml". Stefan From tleeuwenburg at gmail.com Thu Nov 23 19:28:14 2006 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 23 Nov 2006 16:28:14 -0800 Subject: The Python Papers -- letters to the editor Message-ID: <1164328094.918889.62230@k70g2000cwa.googlegroups.com> If anyone would like their comments to appear in The Python Papers, we will need to get your permission to use them under the Creative Commons 2.5 license subject to Noncommercial, Attribution and Share-Alike conditions. For this reason, we request that letters to the editor be emailed to letters at pythonpapers.org, indicating an acceptance of this agreement. Cheers, -T (Editor-In-Chief) From salmoni at gmail.com Tue Nov 14 09:36:28 2006 From: salmoni at gmail.com (Alan J. Salmoni) Date: 14 Nov 2006 06:36:28 -0800 Subject: Programmatically finding "significant" data points In-Reply-To: References: <1163513101.580610.151420@b28g2000cwb.googlegroups.com> Message-ID: <1163514988.269564.293440@b28g2000cwb.googlegroups.com> If the order doesn't matter, you can sort the data and remove x * 0.5 * n where x is the proportion of numbers you want. If you have too many similar values though, this falls down. I suggest you check out quantiles in a good statistics book. Alan. Peter Otten wrote: > erikcw wrote: > > > Hi all, > > > > I have a collection of ordered numerical data in a list. The numbers > > when plotted on a line chart make a low-high-low-high-high-low (random) > > pattern. I need an algorithm to extract the "significant" high and low > > points from this data. > > > > Here is some sample data: > > data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, > > 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, > > 0.10] > > > > In this data, some of the significant points include: > > data[0] > > data[2] > > data[4] > > data[6] > > data[8] > > data[9] > > data[13] > > data[14] > > .... > > > > How do I sort through this data and pull out these points of > > significance? > > I think you are looking for "extrema": > > def w3(items): > items = iter(items) > view = None, items.next(), items.next() > for item in items: > view = view[1:] + (item,) > yield view > > for i, (a, b, c) in enumerate(w3(data)): > if a > b < c: > print i+1, "min", b > elif a < b > c: > print i+1, "max", b > else: > print i+1, "---", b > > Peter From weekender_ny at yahoo.com Tue Nov 21 23:38:49 2006 From: weekender_ny at yahoo.com (John) Date: 21 Nov 2006 20:38:49 -0800 Subject: filling forms automatically generated using javascript Message-ID: <1164170329.515873.311900@h48g2000cwc.googlegroups.com> Is there an automatic way of filling forms that have been generated using javascript? I tried to use python+mechanize but am having trouble with javascript forms. This is the way the form is created: Thanks in advance for your help, --j From steve at ferg.org Sat Nov 25 22:47:17 2006 From: steve at ferg.org (Steve) Date: 25 Nov 2006 19:47:17 -0800 Subject: Python 2.5 idle and print command How do I suppress a line feed? References: <1164310576.767673.297470@h54g2000cwb.googlegroups.com> Message-ID: <1164512837.555705.186620@l39g2000cwd.googlegroups.com> See http://www.ferg.org/projects/python_gotchas.html#contents_item_4 From apardon at forel.vub.ac.be Tue Nov 14 07:01:05 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Nov 2006 12:01:05 GMT Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <17750.22816.636590.485360@montanaro.dyndns.org> <4558B9E3.2040207@hobbshouse.org> Message-ID: On 2006-11-13, Ben Finney wrote: > Michael Hobbs writes: > >> To be clear, this is the actual thrust of my argument. It seems >> redundant to have *both* line continuations and colons in compound >> statements. > > Why are you trying to remove redundancy? Why not? My impression is that removing redundancy is considered a positive thing here in c.p.l. > The language is designed for > communication between people (programmers) primarily. Redundancy is > often the best way to be explicit and readable. Except if you argue for blockmarkers. Then you get the response that indentation is clear enough and such markers are redundant. And there have been other subjects where redundancy was seen as something negative. -- Antoon Pardon From fredrik at pythonware.com Thu Nov 2 11:01:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 02 Nov 2006 17:01:04 +0100 Subject: other ways to check for ? In-Reply-To: <1162478431.624590.29290@m7g2000cwm.googlegroups.com> References: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> <1162477269.980535.202320@h48g2000cwc.googlegroups.com> <1162478431.624590.29290@m7g2000cwm.googlegroups.com> Message-ID: elderic wrote: > I just wanted to know if there was a keyword for functions, too. > > Then u could've done: type(f) is function > quite similar to: type(x) is int but why do you think you need that, when you have callable() ? unless you're doing specialized stuff, there's really no reason to distinguish between function objects and other callables. From bj_666 at gmx.net Thu Nov 9 06:28:25 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 09 Nov 2006 12:28:25 +0100 Subject: Sorted list - how to change it References: <1163065969.593970.165600@b28g2000cwb.googlegroups.com> Message-ID: In , Marc 'BlackJack' Rintsch wrote: > lst = [1, 2, 3, 4, 5] > tmp = list(lst) > while lst == tmp: > random.shuffle(lst) Argh, that fails if the list is empty or contains just one item. lst = [1, 2, 3, 4, 5] if len(lst) > 1: tmp = list(lst) while lst == tmp: random.shuffle(lst) Ciao, Marc 'BlackJack' Rintsch From i80and at gmail.com Tue Nov 7 14:39:47 2006 From: i80and at gmail.com (i80and) Date: 7 Nov 2006 11:39:47 -0800 Subject: Character encoding In-Reply-To: <1162928072.047884.163420@i42g2000cwa.googlegroups.com> References: <1162928072.047884.163420@i42g2000cwa.googlegroups.com> Message-ID: <1162928387.620610.31290@h48g2000cwc.googlegroups.com> I would suggest using string.replace. Simply replace ' ' with ' ' for each time it occurs. It doesn't take too much code. On Nov 7, 1:34 pm, "mp" wrote: > I have html document titles with characters like >,  , and > ‡. How do I decode a string with these values in Python? > > Thanks From steve at REMOVE.THIS.cybersource.com.au Wed Nov 29 19:38:32 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 30 Nov 2006 11:38:32 +1100 Subject: for i in range() anti-pattern [was Re: trouble writing results to files] References: <1164812827.653386.323320@80g2000cwy.googlegroups.com> Message-ID: On Wed, 29 Nov 2006 17:00:30 +0100, Fredrik Lundh wrote: > Neil Cerutti wrote: > >>> BTW, iterating over range(len(a)) is an anti-pattern in Python. >> >> Unless you're modifying elements of a, surely? > > and needs to run on a Python version that doesn't support enumerate. This isn't meant as an argument against using enumerate in the common case, but there are circumstances where iterating with an index variable is the right thing to do. "Anti-pattern" tends to imply that it is always wrong. The advantage of enumerate disappears if you only need to do something to certain items, not all of them: >>> alist = list("abcdefghij") >>> for i in xrange(3, 7, 2): ... print i, alist[i] ... 3 d 5 f Nice and clear. But this is just ugly and wasteful: >>> for i,c in enumerate(alist): ... if i in xrange(3, 7, 2): ... print i, c ... 3 d 5 f although better than the naive alternative using slicing, which is just wrong: >>> for i,c in enumerate(alist[3:7:2]): ... print i, c ... 0 d 1 f The indexes point to the wrong place in the original, non-sliced list, so if you need to modify the original, you have to adjust the indexes by hand: >>> for i,c in enumerate(alist[3:7:2]): ... print 2*i+3, c ... 3 d 5 f And remember that if alist is truly huge, you may take a performance hit due to duplicating all those megabytes of data when you slice it. If you are modifying the original, better to skip making a slice. I wrote a piece of code the other day that had to walk along a list, swapping adjacent elements like this: for i in xrange(0, len(alist)-1, 2): alist[i], alist[i+1] = alist[i+1], alist[i] The version using enumerate is no improvement: for i, x in enumerate(alist[0:len(alist)-1:2]): alist[i*2], alist[i*2+1] = alist[i*2+1], x In my opinion, it actually is harder to understand what it is doing. Swapping two items using "a,b = b,a" is a well known and easily recognised idiom. Swapping two items using "a,b = b,c" is not. -- Steven. From copiernik at wp.pl Fri Nov 10 16:05:16 2006 From: copiernik at wp.pl (consternation) Date: Fri, 10 Nov 2006 22:05:16 +0100 Subject: newbee I have an object how to check what's his class? References: <1163171613.040825.78290@m73g2000cwd.googlegroups.com> Message-ID: I think I know now where my problems come from. I spare you boring implementation code. The case look like this: I parse xml file something a like
1 <\a> 2 <\a> 3 <\a> 4<\b> <\X> <\a> <\a> <\a> <\b> <\X> I succesfully constructlop-level X objects - I see all components when i print X0, X1 out with _repr_. I store my X's in memory. I had some problems with this. I googled, red newsgoup ad foud a solution that seemd to be perfect for me (...till now). In the parser- Y class a have a dictionary def __init__ self.mem={} I googled a way how to add elements to dict, I have read the code not the description below ##copied from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66516 def addItem(self,word,pagenumber): self.mem.setdefault(word,[]).append(pagenumber) ^^^^^^^^ So my dict looks like{ (id of top-level X) 0 : (the X itself) X0, 2 : X2, 4.......... } I wrote it some time and I was tired I haven't pay attention to the breackets at he beginning of outprint TOP LEVEL X WITH ID=0 [ <---- 1<\a> 2<\a> 3<\a> 4<\a> <\class X> <\class X>] One can clearly see it's a list :( Shame on me. I did a trick. If my X object is stored in a list and it's the only element of the list I can simply use it like: print v[0] print" isinstance(x,X)" print isinstance(v[0],X) print "type(x) is X" print type(v[0]) is X print v[0].__class__ print v[0].__class__.__name__ and results <----no [!!!! 1<\a> 2<\a> 3<\a> 4<\a> <\class X> <\class X> isinstance(x,X) True :-) type(x) is X False :( ?? __main__.X X temporarily it solves my probblems I'm just curious why type can't handle the test. Thank you for help, and making me think :-) From icebergwtf at yahoo.com.cn Thu Nov 9 20:58:49 2006 From: icebergwtf at yahoo.com.cn (Tiefeng Wu) Date: Fri, 10 Nov 2006 09:58:49 +0800 (CST) Subject: Simple question to split Message-ID: <20061110015849.99229.qmail@web15014.mail.cnb.yahoo.com> Matthias Winterland wrote: > Hi, > > I have a simple question. When I read in a string like: > a='1,2,3,4,5 6 7,3,4', can I get the list l=[1,2,3,4,5,6,7,3,4] with a > single split-call? > > Thx, > Matthias Sorry, I didn't notice there are spaces between 5 6 7 :{P here is new code: >>> a = "1,2,3,4,5 6 7,3,4" >>> l = [int(n) for n in a.replace(' ',',').split(',')] >>> l [1, 2, 3, 4, 5, 6, 7, 3, 4] >>> wutiefeng 2006-11-10 ___________________________________________________________ ????????-3.5G???20M??? http://cn.mail.yahoo.com From dakman at gmail.com Mon Nov 13 13:11:08 2006 From: dakman at gmail.com (dakman at gmail.com) Date: 13 Nov 2006 10:11:08 -0800 Subject: Is python for me? In-Reply-To: References: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> Message-ID: <1163441468.081643.189600@f16g2000cwb.googlegroups.com> As stated above python is capable of all those things, however on larger applications like that it can tend to slow down a bit. And the executables do need a little bit of work, because it's bassicly a dll and a library of all your .pyc files. However python is still a great language and I would recomend it. And most of these things will probably be fixed in Python 3000! Cameron Laird wrote: > In article <1163437873.721254.31070 at b28g2000cwb.googlegroups.com>, > lennart wrote: > >Hi, > > > >I'm planning to learn a language for 'client' software. Until now, i > >'speak' only some web based languages, like php. As a kid i programmed > >in Basic (CP/M, good old days :'-) ) Now i want to start to learn a > >(for me) new computer language. > > > >I like Python. Its free, easy to learn and some favorite programs of my > >are written in Python / can understand Python (like OpenOffice) etc. > > > >But I'm not a full-time programmer. I know, that I've only time & > >possibility to learn one (= 1) language good. So i ask myself is python > >the language I'm looking for? > > > >In the future, i want to write the following applications: > >[*] A database driven program, which can handle my clients, tasks and > >places (= 3 tables, has to work relative with each other). I think, > >this isn't a problem for Python > >[*] As a photographer i like to build a picture management system (also > >db) with raw support. Raw is the raw-data from the sensor of the > >camera. My questions: > >- can python encode raw? > >- can python head for a utility like dcraw? > >- or head for a utility like IrfanView (delphi?) or something like > >that? > . > . > . > Yes. > > Yes, Python is generally capable in all the roles you describe. > Perhaps most exciting, though, is that you can try out the > language yourself, TODAY, over the next few hours, and, in no > more time than that, get a realistic if limited idea how it's > likely to work for you. With the right introduction http://docs.python.org/tut/ > you can be coding usefully in > Python very quickly. From no-spam at no-spam-no-spam.invalid Wed Nov 8 11:40:39 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 08 Nov 2006 17:40:39 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <1162947569.228388.16940@m7g2000cwm.googlegroups.com> References: <1162947569.228388.16940@m7g2000cwm.googlegroups.com> Message-ID: Sandra-24 wrote: > On Nov 2, 1:32 pm, robert wrote: >> I'd like to use multiple CPU cores for selected time consuming Python computations (incl. numpy/scipy) in a frictionless manner. >> >> Interprocess communication is tedious and out of question, so I thought about simply using a more Python interpreter instances (Py_NewInterpreter) with extra GIL in the same process. > > Why not use IronPython? It's up to date (unlike Jython), has no GIL, > and is cross-platform wherever you can get .NET or Mono (UNIX, macs, > windows) and you can use most any scientific libraries written for the > .NET/Mono platform (there's a lot) Take a look anyway. > > -Sandra what about speed. Is it true that IronPython is almost as fast as C-Python meanwhile? When this all is really true, its probably a proof that putting out LOCK-INC-lock's (on dicts, lists, mutables ...) in CPython to remove the GIL in future should not be really so expensive as it was teached in the past :-) Still to adopt to .NET libraries will be a big step. Is there really a thing out there as usable as numpy/scipy. And GUI programming in IronPython ... ( The FAQ's on codeplex.com and many docs are not readable currently due to site errors. What about overall stability and # of users of Iron as of today? ) -robert From inq1ltd at verizon.net Sun Nov 5 11:51:45 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Sun, 05 Nov 2006 11:51:45 -0500 Subject: disabledforeground or similar for Entry (in Tkinter) In-Reply-To: <200611041952.07546.inq1ltd@verizon.net> References: <1162656214.176092.46530@f16g2000cwb.googlegroups.com> <200611041952.07546.inq1ltd@verizon.net> Message-ID: <200611051151.45268.inq1ltd@verizon.net> Since others want to see more, Try this, you can make the changes you want to the look of your final output with grid or pack_forget() . root = Tk() class Ktest: def __init__(self): self.Ftest1() def Ftest1(self): try: self.test2.grid_forget() except AttributeError : pass self.test1 = Button(root, text='Push #1 button', bg = 'yellow', width = 25, command = self.Ftest2, height = 25) self.test1.grid(row=0, column=0) def Ftest2(self): self.test1.grid_forget() self.test2 = Button(root, text='Push #2 button', bg = 'green', width = 25, command = self.Ftest1, height = 8) self.test2.grid(row=0, column=0) if __name__== '__main__' : Ktest() mainloop() jim-on-linux http://www.inqvista.com > On Saturday 04 November 2006 11:03, Dustan wrote: > > Back in this post, I attempted to make a > > label look like a button: > > http://groups.google.com/group/comp.lang.pyth > >on > > /browse_thread/thread/a83195d3970a6851/2053cb > >aec > > 1bc1f19?auth=DQAAAHkAAAAMDAWnhNnzpuKlwOKZUwAG > >UTt > > T2Ay-EAB7rCY6SnwfnDzZ98M37bZDW2Is0LrBVrr8XEgP > >fcu > > OkiUE-CrSsKbBSX-67voDUXfbATBd0eYNMClezby4EXT2 > >fuL > > m6f0llJ_xMO8BfkjVho_7CZvlf_9tNGnJixTbq8zr21OD > >ZBh ouQ > > > > Alright, I've learned my lesson - don't use a > > new widget; modify the old one. > > > > Except the Entry widget doesn't have a > > disabledforeground option. Neither does the > > Text widget, but IDLE seems to accomplish > > making a disabled Text look the same as an > > enabled Text in the IDLE Help section. > > > > No, foreground (fg) and background (bg) don't > > make a difference; it still changes the color > > of the Entry widget upon disabling. > > > > There must be something I'm missing here... > > My previous post was hasty and we all know, > "Haste makes waste." > > Try this; > > If you use wiget-01.pack_forget() or > wiget-01.grid_forget(), you can now build > wiget-02 using wiget-02.pack or grid() for the > same location. > > You can reinstall uninstalled wigets by using > pack() or grid() again for those hidden wigets. > However only after uninstalling for the wigets > in those locations. > > > > root = Tk() > > test1 = Button(root, text='Test No.1 button', > bg = 'yellow', width = 15, height = 10) > test1.grid(row=0, column=0) > test1.grid_forget() > > > test2 = Button(root, text='Test #2 button', bg > = 'green', width = 15, height = 10) > test2.grid(row=0, column=0) > > mainloop() > > > jim-on-linux > > http://www.inqvista.com From djh at dgh-aalborg.dk Thu Nov 30 18:45:22 2006 From: djh at dgh-aalborg.dk (Reynold) Date: Thu, 30 Nov 2006 15:45:22 -0800 Subject: gratuity sharply Message-ID: <000701c714da$39a6d790$5921aa4c@cfmapj> "It's clear Brad is being a jerk. This blog is for people who want to think about how they manage people, projects, and risk. For me, project management planning is the identification of release criteria and other prose about the project. But we don't always have all the clues, as I didn't in this conversation. But by not asking for help earlier, I might cause that to happen. I'm not sure why that was so hard to do. Is this a good time to talk? Even when I edit, I add more. " If anyone asks about Brad's jerkiness problems, you say, "Brad has decided to pursue career opportunities elsewhere. And in most circumstances, I manage to straight-talk without hurting anyone, even myself. Even when I edit, I add more. And some of us jump to conclusions quickly with the clues we have. But when I hook it up to my computer for scanning to a file, it falls apart. I have a picture that I want to simplify but I don't know Omnigraffle well enough to do so. Ok, I quit all the applications and leave my computer alone to install. Even when I edit, I add more. And some of us jump to conclusions quickly with the clues we have. I now know how to do this for the next time. Check out the Gifts with Purchase page too! You create a lack of trust by commenting about other people. Implicit requirements are still requirements. But that wasn't the case earlier this week. " We went on from there. I can do other things while I'm downloading. Well, I'm only sort-of happy. So does the swapping back in, if it's been a long time since I last worked on this task. Even though I managed to accomplish the tasks I needed, the time it took me to accomplish them and the foreign approach to the UI made me not happy. I was ready to throw the damn thing out the window when I thought, "Huh, I bet other people have this problem. If you're in flow, this is surprisingly high. I was able to start scanning and save my files. Luckily, Nice Person seemed to have taken it well. Even though I managed to accomplish the tasks I needed, the time it took me to accomplish them and the foreign approach to the UI made me not happy. Certainly, for some tasks, it's fairly trivial. So instead of making myself crazy trying to write more good stuff for you, I decided you should read these. Those implicit requirements are still requirements. And if you have to fire Brad, you say something like, "Brad has decided to pursue career opportunities elsewhere. I started to download. Ok, I'm a smart person, I can figure this out. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: anthem.gif Type: image/gif Size: 8716 bytes Desc: not available URL: From "svein at seldal dot com" at STARDUST.DNSALIAS.com Wed Nov 8 14:16:44 2006 From: "svein at seldal dot com" at STARDUST.DNSALIAS.com (Svein Seldal) Date: Wed, 08 Nov 2006 20:16:44 +0100 Subject: Delivering data to python from a c-thread In-Reply-To: References: Message-ID: <20061108191627.B20DFC4A8@stardust.seldal.com> Steve Holden wrote: > OK. I was just thinking that, with Python threads, communication using > Queue.Queue is thread-safe and will handle the GIL, so that way you only > have the problem of how to synchronize your C code when it receives the > callback from the Python thread. The python internal thread-safe problem is under control. I'm using twisted, so it already provide me with a thread-synchronization mechanism (the reactor.callFromThread() ). The issue is rather the C sync-ing. I'm kind of new to multithreaded (pthreads) programming, so I'm not quite sure what exists of functionality and functions. So this is how I think of doing it: Setup a mailbox or similar where the producing thread will deliver its message. This call to the mailbox should block until the consumer thread has received the message. My py thread will repeatedly call my C-handler. This C handler will wait (forever) for incoming messages from the producer. This should work, right? I mean, this could even be implemented with flags/semaphores and let the data be transferred over ordinary common global variables. Francly, I think the best solution would be to be able to call py from two independent c-treads! Regads, Svein Seldal From siona at chiark.greenend.org.uk Mon Nov 6 10:33:16 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 06 Nov 2006 15:33:16 +0000 (GMT) Subject: Sorted and reversed on huge dict ? References: <1162580533.981364.211860@h54g2000cwb.googlegroups.com> <7xvelwib1b.fsf@ruckus.brouhaha.com> <1162590153.024233.311670@b28g2000cwb.googlegroups.com> Message-ID: wrote: >so i just have tried, even if i think it will not go to the end => i >was wrong : it is around 1.400.000 entries by dict... > >but maybe if keys of dicts are not duplicated in memory it can be done >(as all dicts will have the same keys, with different (count) values)? I've had programs handling dicts with 1.7million items and it isn't a great problem, providing you're careful not to duplicate data. Creating a copy of keys() in a separate list, for example, will inflate memory usage noticably. >memory is 4Gb of ram, [ ... ] Unless you're on a 64bit OS, that's irrelevant. You'll hit the 2G per-process limit before you start putting a strain on real memory. -- \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" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From peter.maas at somewhere.com Mon Nov 13 13:08:57 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Mon, 13 Nov 2006 19:08:57 +0100 Subject: explicit self revisited In-Reply-To: <1163407870.637052.32760@m73g2000cwd.googlegroups.com> References: <1163407870.637052.32760@m73g2000cwd.googlegroups.com> Message-ID: Michele Simionato wrote: > Peter Maas wrote: >> All these reasons are valid and retained by the following suggestion: let >> self be represented by the dot > > This suggestion has been discussed in the past (I remember having the > same idea myself when I first learned Python). But at the end I believe > the explicit 'self' is a better solution, because there are cases where > it is useful to have it Thanks, Michele. My intention wasn't to abandon explicit self but to replace it by a shorter and unique entity. I searched a little for similar suggestions in the past but didn't find them so I decided to post. I admit that my suggestion was half-baked. But at least I learned something: a heated debate isn't bound to become an endless thread if the OP abstains from answering idiot replies ;) -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From shejo284 at gmail.com Tue Nov 7 15:48:45 2006 From: shejo284 at gmail.com (Sheldon) Date: 7 Nov 2006 12:48:45 -0800 Subject: C wrapper In-Reply-To: References: <1162928252.643092.23350@h48g2000cwc.googlegroups.com> <1162930226.658619.79830@m73g2000cwd.googlegroups.com> <1162931220.448328.108160@e3g2000cwe.googlegroups.com> Message-ID: <1162932525.586346.324050@h48g2000cwc.googlegroups.com> Gabriel Genellina skrev: > At Tuesday 7/11/2006 17:27, Sheldon wrote: > > >Here is the file/module name: _msgpps_functions.c > >Here is the initfunction: > > > >PyMODINIT_FUNC init_msgpps_functions(void) { > > PyObject* m; > > m=Py_InitModule("_msgpps_functions",_msgpps_functionsMethods); > > ErrorObject = PyString_FromString("_msgpps_functions.error"); > > if(ErrorObject == NULL || \ > > PyDict_SetItemString(PyModule_GetDict(m),"error",ErrorObject)!=0) > >{ > > Py_FatalError("Can't define _msgpps_functions.error"); > > import_array(); > > } /* access to Numeric PyArray functions */ > >} > > > > > >I have not main() function in the file. Instead the main function is > >called the same name: > > > >static PyObject* _msgpps_functions(PyObject* self, PyObject* args) > > > >Now I am new at this and I have been reading anything I can find. The > >only thing that is out of place is the part which I didn't include: > > > > /* Initialize the Python interpreter. Required. */ > > Py_Initialize(); > > > > /* Add a static module */ > > initspam(); > >because I still don't understand this part. > > Are you *extending* Python with a new module written in C (you should > be using the first part), > or *embedding* python inside your application, mainly written in C > (you would use something like the last code). > > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! > ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar Ok, This I have done but still, the same error message. :( From steve at REMOVEME.cybersource.com.au Fri Nov 17 00:09:23 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 17 Nov 2006 16:09:23 +1100 Subject: How fuzzy is get_close_matches() in difflib? References: <1163724049.225348.118020@h54g2000cwb.googlegroups.com> <1163737190.118975.227740@h48g2000cwc.googlegroups.com> Message-ID: On Thu, 16 Nov 2006 20:19:50 -0800, John Henry wrote: > I did try them and I am impressed. It helped me found a lot of useful > info. I just want to get a feel as to what constitutes a "match". The source code has lots of comments, but they don't explain the basic algorithm (at least not in the difflib.py supplied with Python 2.3). There is no single diff algorithm, but I believe that the basic idea is to look for insertions and/or deletions of strings. If you want more detail, google "diff". Once you have a list of differences, the closest match is the search string with the fewest differences. As for getting a feel of what constitutes a match, I really can't make any better suggestion than just try lots of examples with the interactive Python shell. -- Steven D'Aprano From simonwittber at gmail.com Mon Nov 6 19:41:41 2006 From: simonwittber at gmail.com (Simon Wittber) Date: 6 Nov 2006 16:41:41 -0800 Subject: Python Distilled In-Reply-To: <08Odnc6j7uKLxtLYnZ2dnUVZ_oydnZ2d@comcast.com> References: <1162790565.418382.237050@m73g2000cwd.googlegroups.com> <08Odnc6j7uKLxtLYnZ2dnUVZ_oydnZ2d@comcast.com> Message-ID: <1162860101.746321.73770@h54g2000cwb.googlegroups.com> > http://www.python.org/dev/summary/2006-09-16_2006-09-30/#shrinking-python Excellent, just what I was hoping for. Thanks! -Sw. From robert.kern at gmail.com Sat Nov 11 07:09:49 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 11 Nov 2006 06:09:49 -0600 Subject: numpy/scipy: correlation In-Reply-To: References: Message-ID: robert wrote: > Is there a ready made function in numpy/scipy to compute the correlation y=mx+o of an X and Y fast: > m, m-err, o, o-err, r-coef,r-coef-err ? numpy and scipy questions are best asked on their lists, not here. There are a number of people who know the capabilities of numpy and scipy through and through, but most of them don't hang out on comp.lang.python. http://www.scipy.org/Mailing_Lists scipy.optimize.leastsq() can be told to return the covariance matrix of the estimated parameters (m and o in your example; I have no idea what you think r-coeff is). -- 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 holdenweb.com Wed Nov 1 21:35:53 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 02 Nov 2006 02:35:53 +0000 Subject: re question In-Reply-To: References: Message-ID: Sch?le Daniel wrote: > Hello all, > > I didn't found more appropriate news group for > this question, please let me know if there is ng with > regular expression as its main topic > > I am trying to construct a case where a greedy and > non greedy operation produce different result. > I dont see the difference between 'a??b' and 'a?b' > As far I understand is that ? will first try to match a > (it's greedy) and only if it fails then it step back > and lets a unmatched. The other doesn't match a at first, > only if the pattern fails to match it steps back and match a. > > But don't they do eventually the same thing? > Can someone provide an example where 2 patterns yield > different results. > >>> target = "

Sample String

" >>> greedy = re.compile("<.+>") >>> nongreedy = re.compile("<.+?>") >>> m1 = greedy.match(target) >>> m2 = nongreedy.match(target) >>> m1.group(0) '

Sample String

' >>> m2.group(0) '

' >>> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From elderic at ish.de Thu Nov 2 05:06:49 2006 From: elderic at ish.de (elderic) Date: 2 Nov 2006 02:06:49 -0800 Subject: other ways to check for ? Message-ID: <1162462009.134922.283410@i42g2000cwa.googlegroups.com> Hi there, are there other ways than the ones below to check for in a python script? (partly inspired by wrapping Tkinter :P) def f(): print "This is f(). Godspeed!" 1.: --> sort of clumsy and discouraged by the docs as far as I read import types type(f) is types.FunctionType 2.: --> I don't like this one at all def null(): pass type(f) is type(null) Basically I'm searching for something like: "type(f) is func" like in: "type(x) is int" Any ideas? =) From news at p2b.datatailors.com Wed Nov 8 14:51:49 2006 From: news at p2b.datatailors.com (Peter van Kampen) Date: 08 Nov 2006 19:51:49 GMT Subject: Is there a commas-in-between idiom? References: Message-ID: On 2006-11-06, Fredrik Lundh wrote: > I've collected a bunch of list pydioms and other notes here: > > http://effbot.org/zone/python-list.htm """ A = B = [] # both names will point to the same list """ I've been bitten by this once or twice in the past, but I have always wondered what it was useful for? Can anybody enlighten me? TIA, PterK -- Peter van Kampen pterk -- at -- datatailors.com From antonioskatsikadamos at yahoo.com Wed Nov 8 10:47:01 2006 From: antonioskatsikadamos at yahoo.com (Antonios Katsikadamos) Date: Wed, 8 Nov 2006 07:47:01 -0800 (PST) Subject: Python Error:IndentationError: expected an indented block Message-ID: <20061108154702.61516.qmail@web58107.mail.re3.yahoo.com> hi all. I try to run an old python code and i get the following message File "/home/antonis/db/access.py", line 119 def DoCsubnet1 (action, subject, target, args): # DoC servers net ^ IndentationError: expected an indented block 1) and I don't know what causes it. I would be grate full if you could give me a tip. 2) how can i overcome it? Can i use the keyword pass?and if how ccan i use it Kind regards, Antonios --------------------------------- Sponsored Link For just $24.99/mo., Vonage offers unlimited local and long- distance calling. Sign up now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Mon Nov 13 13:22:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Nov 2006 19:22:38 +0100 Subject: httplib.ResponseNotReady question In-Reply-To: <1163441112.359818.208520@m7g2000cwm.googlegroups.com> References: <1163441112.359818.208520@m7g2000cwm.googlegroups.com> Message-ID: Max wrote: > If I run this with loops=1 then everything works fine. If I use a > number greater than 1 then I get the error. Is there a method call > that I need to restore the requestor object to a condition where it's > eligible to receive another response? I'm pretty sure that to get a new response from the server, you need to make a new request. From bjourne at gmail.com Sun Nov 5 17:32:48 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 5 Nov 2006 23:32:48 +0100 Subject: Projecting MUD maps Message-ID: <740c3aec0611051432v4bb92f2gc7fa7a933954f64f@mail.gmail.com> Hello, I'm looking for an algorithm to project "MUD maps" such as the following map: http://www.aww-mud.org/maps/MUD_Maps/Caerin-colour.jpg MUD:s consists of rooms, each rooms has up to four orthogonal edges (north, east, west and south) that connects it to another room. So it is very easy to model a MUD as a directed graph. But projecting the graph on a surface is very complicated. For example, Room A:s North edge may connect it to Room B. But Room B:s South edge may connect it to Room C. Or another tricky example: Room A:s East edge connects it to Room B, whose East edge connect it to Room C, whose North edge connects it to Room D, whose West edge connects it to Room E, whose South edge connects it to Room A. In that example, there would be a "hole" between Room D and E. -- mvh Bj?rn From sjmachin at lexicon.net Mon Nov 20 14:11:15 2006 From: sjmachin at lexicon.net (John Machin) Date: 20 Nov 2006 11:11:15 -0800 Subject: cPickle problems References: <1163722893.992949.295350@b28g2000cwb.googlegroups.com> <1163723175.530850.185990@m73g2000cwd.googlegroups.com> <1163724509.572724.199720@f16g2000cwb.googlegroups.com> <1163730111.641857.142850@k70g2000cwa.googlegroups.com> <1164039181.157901.72130@m73g2000cwd.googlegroups.com> Message-ID: <1164049874.977314.227330@k70g2000cwa.googlegroups.com> Jeff Poole wrote: > > Jeff - > > > > Sorry not to reply sooner, I have been out of town with limited access to > > c.l.py. Also, I didn't really pick up on "cPickle problems" as a > > pyparsing-related post. :) > > :-) Choice of keywords is important -- for example, "Excel" always grabs my attention. In this case, the keyword the OP should have used is not "cPickle" but "re" :-) [snip] > > > > -- Paul > > Paul, > > No problem, I think we've both been busy with other things. I was > actually going to post something on the PyParsing wikispaces since I > wasn't sure if you checked here. :-) I suggest that the OP take his googler back to the shop he bought it from; it is severely damaged. :-) HTH, John From tleeuwenburg at gmail.com Thu Nov 23 18:15:35 2006 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 23 Nov 2006 15:15:35 -0800 Subject: PDF to HTML conversion for The Python Papers In-Reply-To: <1164253034.295391.56720@j44g2000cwa.googlegroups.com> References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <1164106267.882164.124670@h48g2000cwc.googlegroups.com> <1164156093.359433.315790@e3g2000cwe.googlegroups.com> <1164244166.988532.261370@l39g2000cwd.googlegroups.com> <1164253034.295391.56720@j44g2000cwa.googlegroups.com> Message-ID: <1164323735.492524.48620@j44g2000cwa.googlegroups.com> Eric_Dexter at msn.com wrote: > The adobe people have online conversion > > http://www.adobe.com/products/acrobat/access_onlinetools.html > > google seems to convert them when they end up in the engines > > http://www.google.com/search?hl=en&q=pdf+to+html > > has a list of converters > > http://www.dexrow.com The adobe online version crashed on the PDF I sent it, which may be fractionally different from the one currently available. I haven't tried the others, but I don't feel good about it. However, maybe I should try a few... If anyone here feels like trying and has any success, I'd be happy to hear it. Cheers, -T (Editor-In-Chief) From evenprimes at gmail.com Thu Nov 9 14:52:25 2006 From: evenprimes at gmail.com (Chris Cioffi) Date: Thu, 9 Nov 2006 14:52:25 -0500 Subject: Do I want multidispatch or object plug-ins or something else? Message-ID: Hello all, I've got an EDI parsing application written in Python that is becoming unwieldy to maintain. At a high level here's what it does: 1. Loops through the EDI message 1 segment at a time (think SAX XML...) 2. Once it identifies what type of transaction is being processed it creates a "sub-parser" specifically for that transaction type 3. The sub-parser marks up the EDI into HTML and extracts a fair number of statistics about the transactions. Now, my sub-parser classes are polymorphic and I've used the hierarchy to make sure I don't have repeated code in each class. HOWEVER, I'm finding it difficult to add new statistic gathering methods because the code is already rather complex. That leads me to think I've got bad design. What I _think_ I want is a way to register plug-ins that say "I work with transactions of type X,Y,Z" and then have the sub parser string together calls to the various plug-ins. The "master" sub-parser would handle the basic EDI -> HTML formatting and the plug-ins would handle gathering any statistics. I currently use introspection to figure out what segments sub-parsers are interested in and I figure I would keep doing that in the future. Can anyone point me to either an on-line or off-line resource I could use for this type of thing? Are there established "plug-in patterns" already? Part of why I'm asking is because I don't think I even have the right vocabulary to describe what I'm trying to do. Any pointers would be appreciated! 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 bblais at bryant.edu Sat Nov 25 11:57:30 2006 From: bblais at bryant.edu (Brian Blais) Date: Sat, 25 Nov 2006 11:57:30 -0500 Subject: About alternatives to Matlab In-Reply-To: <1164331082.270046.290720@l39g2000cwd.googlegroups.com> References: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> <1163711343.870829.110030@h48g2000cwc.googlegroups.com> <1163720268.611923.3180@e3g2000cwe.googlegroups.com> <1164331082.270046.290720@l39g2000cwd.googlegroups.com> Message-ID: <456875FA.1000209@bryant.edu> Phil Schmidt wrote: > > I'd love to use Python, but I'm not comfortable with the hardware side > of that. I'm certain that most, if not all data acquisition hardware > comes with DLL drivers, which I could interface with using ctypes. I'm > concerned though about spending more time messing around with the > hardware interface than it's worth. > > Do you have any experience with this side of the Matlab replacement > question? How about anyone else? Any recommendations? > Unfortunately, no I don't have experience with the hardware end of things. One can, both with c-types and with pyrex, very easily use existing C libraries so if there is a C-API, that shouldn't be a problem. Sorry for not being much help! bb -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From bill.pursell at gmail.com Tue Nov 21 01:08:27 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 20 Nov 2006 22:08:27 -0800 Subject: Vim scripts for editing Python? In-Reply-To: <1164086261.774376.125490@j44g2000cwa.googlegroups.com> References: <1164086261.774376.125490@j44g2000cwa.googlegroups.com> Message-ID: <1164089307.390351.263980@j44g2000cwa.googlegroups.com> Rainy wrote: > Hi, did anyone make a good set of scripts for editing Python in Vim? I > know there is one on vim.org but it isn't very advanced. thx.. What functionality are you looking for? From tgrav at mac.com Fri Nov 3 18:57:49 2006 From: tgrav at mac.com (Tommy Grav) Date: Fri, 3 Nov 2006 18:57:49 -0500 Subject: Physical constants Message-ID: <73D46C5F-12AE-4700-86D2-7FAE0DEF6C54@mac.com> I have some code for doing orbital computations. The code is kind of extensive with many classes, each having several functions. In these functions I need to use constants (like the gravitational constant). What is the best way of implementing a solution when constants are used in several different classes and functions? I do not want to pass the constant down through the functions. I have thought of making a class of constants but I do not want to invoke an instant in each function. How is the pi and e constants in math coded? Tommy tgrav at mac.com http://homepage.mac.com/tgrav/ "Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genious -- and a lot of courage -- to move in the opposite direction" -- Albert Einstein -------------- next part -------------- An HTML attachment was scrubbed... URL: From noreply at nospam.it Fri Nov 10 12:01:02 2006 From: noreply at nospam.it (Danny Scalenotti) Date: Fri, 10 Nov 2006 18:01:02 +0100 Subject: newbie: minidom Message-ID: I'm not able to get out of this ....... from xml.dom.minidom import getDOMImplementation impl = getDOMImplementation() // default UTF-8 doc = impl.createDocument(None, "test",None) root = doc.documentElement root.setAttribute('myattrib', '5') print root.toxml() I obtain why not this? thanks From martin.dion at gmail.com Mon Nov 6 15:08:13 2006 From: martin.dion at gmail.com (martdi) Date: 6 Nov 2006 12:08:13 -0800 Subject: adding python scripting to my application In-Reply-To: <1162840279.875373.301550@f16g2000cwb.googlegroups.com> References: <1162794251.047389.297800@e3g2000cwe.googlegroups.com> <1162840279.875373.301550@f16g2000cwb.googlegroups.com> Message-ID: <1162843693.517313.286480@m73g2000cwd.googlegroups.com> Jerry wrote: > I am not a Python guru by any means, but I believe that when an > application says that you can "script" their application with Python, > it means that you can actually write Python code to interact with the > application. Embedding may be the same thing. Extending (as I read > it) involves writing portions of your program in Python and have do the > logic portions. > > If you would like to allow users to write small scripts that interact > with your program and control it (a la VBScript or AppleScript), then I > believe embedding Python in your program is what you want. > > If you would like Python to run various parts of your program in order > to make some portions easier to write/manage/whatever, then you want to > "extend" your program using Python. > > The key difference being that you aren't providing a way for someone > else to interact with your program using Python if you are extending. > > Again, I am not a guru and a read through the docs on python.org would > probably be the best place to get sound technical advice on these > subjects. > > -- > Jerry I'm not sure either, but I though Extending was making the C/C++ Code available from Python, while Embedding was making Python Code Available in your app. From nun at example.com Sun Nov 12 15:08:02 2006 From: nun at example.com (Mitja Trampus) Date: Sun, 12 Nov 2006 21:08:02 +0100 Subject: Random image text generation? In-Reply-To: References: Message-ID: skip at pobox.com wrote: > Is there a module out there that will generate an image with a random text > string such as the confirmation images you see on various websites? They're called captcha images or captchas for short. Googling for "python captcha" returns several hits; see what you like... From paddy3118 at netscape.net Wed Nov 8 13:42:00 2006 From: paddy3118 at netscape.net (Paddy) Date: 8 Nov 2006 10:42:00 -0800 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> Message-ID: <1163011320.632781.53370@m7g2000cwm.googlegroups.com> Aahz wrote: > In article <1162997345.277966.31860 at h48g2000cwc.googlegroups.com>, > Beliavsky wrote: > > > >If this is supposed to justify using bad language in a public forum, > >it is poorly reasoned. Having heard "f***" does not mean they were not > >annoyed. 100% of people have seen trash on the street, but that does > >not justify littering. If a group of people don't mind profanity, there > >is no harm in their swearing to each other. But Usenet is read by a > >wide range of people, and needlessly offending some of them is wrong. > >The OP used "f******" just for emphasis. English is a rich language, > >and there are better ways of doing that. > > Oh, gimme a f****** break. Do a simple Gooja search to find out how > often people already use "f***" around here. I think you're the one who > needs to justify your position. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > I too know your wrong Aahz. The written word is not the same as that spoken. People should make an effort to put across their meaning in a clear manner. If I were going to an interview I would be very careful about swearing and most likely not do it. People complain about the friendliness and tone of groups, and mention it when talking about programming languages. Not everyone swears like Eddy Murphy in Beverley Hills Cop, and a lot of those that do, would not do so when they want to impress, or communicate with a stranger. The tone of comp.lang.python *is* an asset, I think, to Python that swearing will diminish. - Paddy. P.S. I did a google search and found 540,000 hits for python in c.l.p. and only 121 for f***. thats less than one in a thousand. Lets keep it that way please. From jeremy+complangpython at jeremysanders.net Fri Nov 10 07:04:57 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Fri, 10 Nov 2006 12:04:57 +0000 Subject: How to choose the right GUI toolkit ? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <1163092380.301382.113470@m7g2000cwm.googlegroups.com> <45536639$0$23587$426a34cc@news.free.fr> <1163099166.793869.271900@h48g2000cwc.googlegroups.com> Message-ID: Dan Lenski wrote: > My apologies! I'm glad to be corrected on this. There are Cygwin > packages for Qt as well, but I have heard about enough bugs to think I > should avoid Qt. I have used enough Gtk apps that run flawlessly under > Windows to have my hopes that it works well. You normally use PyQt/Qt on Windows without Cygwin. There are very few bugs and lots of professional companies base their products on Qt Windows. -- Jeremy Sanders http://www.jeremysanders.net/ From rganesan at myrealbox.com Tue Nov 14 09:36:58 2006 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Tue, 14 Nov 2006 20:06:58 +0530 Subject: Programmatically finding "significant" data points References: <1163513101.580610.151420@b28g2000cwb.googlegroups.com> Message-ID: >>>>> Jeremy Sanders writes: >> How do I sort through this data and pull out these points of >> significance? > Get a book on statistics. One idea is as follows. If you expect the points > to be centred around a single value, you can calculate the median or mean > of the points, calculate their standard deviation (aka spread), and remove > points which are more than N-times the standard deviation from the median. Standard deviation was the first thought that jumped to my mind too. However, that's not what the OP is after. He's seems to be looking for points when the direction changes. Ganesan -- Ganesan Rajagopal From bignose+hates-spam at benfinney.id.au Tue Nov 21 20:15:04 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 22 Nov 2006 12:15:04 +1100 Subject: Trying to understand Python objects References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> Message-ID: <87fyccwacn.fsf@benfinney.id.au> "walterbyrd" writes: > Reading "Think Like a Computer Scientist" I am not sure I understand > the way it describes the way objects work with Python. Congratulations for taking the effort to figure it out, and for thinking about the questions you want answered. > 1) Can attributes can added just anywhere? I create an object called > point, then I can add attributes any time, and at any place in the > program? Generally, yes. It's up to the programmer to do so in a way that's readable and makes sense to later readers. There are conventions, of course, and you should ask about anything specific that confuses you. One convention that you seem to be unaware of is that assigning attributes outside of the class's methods is unusual. This is only a convention, though, and not enforced by the language; on the uncommon occasions you need to add attributes to an instance outside that class's methods, you're not prevented from doing it. > 2) Are classes typically created like this: > > class Point: > pass Typically, classes are created as a subclass of another class. The top-level basic type in Python is 'object', so if your class doesn't make sense deriving from anything else, derive from 'object'. class Point(object): pass Defining a class with *no* superclass is not recommended. If you don't yet understand the difference between the above style (called a "new-style" class) and the style you presented, you should always derive from a superclass ('object' or something more specific) until you encounter a situation where that causes a problem. > Then attributes are added at some other time? No. Typically, the desired attributes are added either to the class when it is defined, resulting in an attribute value that is shared by all instances of that class:: class Point(object): spam = 4 Or, the attributes are added to a specific instance (often in the initialisation method) so that each instance has a separate attribute with the same name:: class Point(object): spam = 4 def __init__(self): eggs = 2 > 3) What is with the __underscores__ ?? Another convention. Names of the form '__foo__' are a signal to the reader that this name will be treated specially; often the internals of Python syntax or some builtin type will look for those names when performing behind-the-scenes magic. For instance, the '__init__' attribute of a class is expected to be a function, and that function is called by Python's instance creation steps immediately after the creation of an instance. Thus, it is used to "initialise" the newly-created instance of the class, doing things specific to that instance. > 4) Are parameters passed to an class definition? > > class Whatever(params): > pass The parameters of the class definition are the super-classes from which this class should inherit its attributes. They don't correspond with the parameters to the class constructor. When you create a new instance of a class, its constructor is called to create the new instance, and then the initialiser is called, to perform post-creation steps on the new instance. This all occurs in one step, as far as the code that called the constructor is concerned. Unlike in many other languages, you will rarely need to define a constructor ('__new__') for your Python classes. It's far more common to let the default constructor create the object, and have any initialisation steps on the newly-created instance performed in the class '__init__' method. The __init__ method gets called by Python's internals (hence the "special" name with underscores) immediately after the creation of the instance. It is called with parameters consisting of the newly-created instance object, followed by all the parameters that were passed to the constructor. origin = Point(0, 0) This will call the constructor of the Point class, which will create a new instance; then, the __init__ method of the Point class will be called with the parameters (, 0, 0). This means the function has access to the specific instance, and can modify it accordingly. The convention is to use 'self' as the name to refer to the first parameter to instance methods, so that the instance object is referred to by the parameter name 'self' in that method. class Point(object): spam = 4 def __init__(self, x_coord, y_coord): if x_coord < 0: x_coord = 0 if y_coord < 0: y_coord = 0 self.x = x_coord self.y = y_coord This initialisation method does a bit of value fudging, then assigns values to attributes of the instance, named 'self' in the context of the method. After the constructor and the __init__ method have finished, the program continues at the point where the constructor was called. Thus, the attributes assigned to the instance are immediately available:: origin = Point(0, 0) print origin.x -- \ "Anyone who believes exponential growth can go on forever in a | `\ finite world is either a madman or an economist." -- Kenneth | _o__) Boulding | Ben Finney From __peter__ at web.de Mon Nov 20 03:58:50 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 20 Nov 2006 09:58:50 +0100 Subject: fileinput.input('test.txt') => ERROR: input() already active References: <1164011174.630226.91580@j44g2000cwa.googlegroups.com> Message-ID: cyberco wrote: > Using fileinput.input('test.txt') I probably forgot to process all > lines or so, since I get the error 'input() already active' when i try > to call fileinput.input('test.txt') again. But how can I 'close' the > previous version I opened? I have no handle to it or so... fileinput.close() Or you forego the global FileInput instance with fi = fileinput.FileInput(...) for line in fi: # process line fi.close() Personally, I use ordinary files instead. Peter From harry.g.george at boeing.com Fri Nov 10 09:14:43 2006 From: harry.g.george at boeing.com (Harry George) Date: Fri, 10 Nov 2006 14:14:43 GMT Subject: manual eggs downloads? Message-ID: "eggs" are wonderful for no-hassle get-all-the-dependencies. However, they can trigger hands-off downloads from various sites. This is Bad News for corporate environments in which every download is carefully pre-approved. A tarball with a subdirectory of "third_party" packages is ok. A web page simple listing the third party sites and the recommended downloads is ok. Automatically downloading is not ok. Is there some way in the eggs mechanism to just get a list of the proposed downloads, and let the user take the actions manually? -- Harry George PLM Engineering Architecture From pavlovevidence at gmail.com Tue Nov 7 15:03:23 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 7 Nov 2006 12:03:23 -0800 Subject: __init__ function problem References: <1162905967.354604.38230@k70g2000cwa.googlegroups.com> Message-ID: <1162929803.735097.279460@i42g2000cwa.googlegroups.com> kelin,zzf818 at gmail.com wrote: > It says the __init__ is called immediately after an instance of the > class is created. What dose "immediately" mean? > And what is difference between the init method and the constructor in > Java? For all intents and purposes, __init__ is a constructor. It isn't technically, but you use it exactly the same way you use constructors in C++ and Java (well, acutally, Python __init__ is a quite bit more flexible, though also less convenient in many cases). Don't worry that it isn't called a constructor. In Python, the real constructor is called __new__, but you shouldn't use __new__ like C++ and Java constructors. Usually there's no reason to use __new__ at all. (The main use case is to return something other than a newly created object, such as a preallocated or cached object. For your normally functioning classes, you should use __init__.) Carl Banks From inq1ltd at verizon.net Fri Nov 24 19:19:33 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Fri, 24 Nov 2006 19:19:33 -0500 Subject: Access to variable from external imported module In-Reply-To: References: <1164316786.875306.276460@h54g2000cwb.googlegroups.com> Message-ID: <200611241919.34161.inq1ltd@verizon.net> The TRS-80 I bought came with both Basic and Assembly Language teaching guides, and that was it. To make the machine work one had to program. I didn't mean to imply that Bill Gates developed it. It's well known that MS borrowed stuff when they needed to from where ever the could get it. That's business. I'm not an MS fan but Bill Gates was the one who gave away a very cheep, borrowed but improved, copy of DOS to computer sellers. These copies could also be copied to floppies (8 inch). So, DOS 3.3 was used by computer sellers, to install DOS on the buyers machine, (intel 286) free. On the other hand, IBM sold the same package for $50.00. I got the free copy of MS 3.3 with my 286. After that, Windows 3.0 cost me $25.00, Windows 3.1 cost me $30.00, DOS upgrade from3.3 to 6.22 cost me $55.00. Since then I purchased Win 95, $100.00 and Win 98. $125.00. And, all for testing software that I produced for people that use that stuff. Bill Gates probably can't program any software to write "Hello World" on any screen, but I'll bet he knows how to fill out a deposit ticket. I think Bill Gates recognize early that the money is in the marketing of the product, not the programming of it. How else can you explain the success of Windows, like it or not? jim-on-linux http://www.inqvista.com On Friday 24 November 2006 17:18, Dennis Lee Bieber wrote: > On Fri, 24 Nov 2006 16:56:58 -0500, > jim-on-linux > > declaimed the following in comp.lang.python: > > That was when bill gates just left Harvard, > > basic was brand new, and 4k of memory was > > Pardon? I'd learned BASIC back around 1972, in > the 9th grade, using an ASR-33 with dial-up to > some company's Honeywell-Bull system. > > BASIC is one of the ancients in languages, > predating Pascal and C. > > Just because Gates managed to scrabble > together a BASIC interpreter for the MITS > Altair, and then had it picked up by other > makers of 8080/Z-80 based "microcomputers" > doesn't make it "brand new". (Personally, I > suspect he hasn't done any programming ever > since that day, and is probably still trying to > find some way to sue Kemeny&Kurtz (sp?s) over > their own creation) > -- > 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 Eric_Dexter at msn.com Wed Nov 1 20:47:15 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 1 Nov 2006 17:47:15 -0800 Subject: trying to call main function with execfile with two arguments In-Reply-To: <1162431477.292694.201900@h54g2000cwb.googlegroups.com> References: <1162431477.292694.201900@h54g2000cwb.googlegroups.com> Message-ID: <1162432035.292978.62920@m73g2000cwd.googlegroups.com> To extend and revise my notes this is the dialog box that comes with boa constructor with very little change. Eric_Dexter at msn.com wrote: > I was trying to find out what my value for filename is but it will not > print. The file I am calling csoundgrid2.main seems to work fine when > I call it directly from spe with two values and I have used this file > dialog to load other files the error I am getting is. thanks for any > help in advance > > File "C:\Python24\Lib\site-packages\boa-constructor\test of > snake\csoundgrid2.py", line 35, in loadFile > infile = open(sys.argv[1], 'r') #The first argument passed in is the > file name > IndexError: list index out of range > > def sco_editor(self): > "Pick a sco file and load it into a sco editor" > dlg = wx.FileDialog(self,"load sco file", ".", "", "*.sco", > wx.OPEN) > try: > if dlg.ShowModal() == wx.ID_OK: > filename = dlg.GetPath() > # Your code > print filename > csoundgrid2.main(filename, """;""") > #("csoundgrid2.py", filename ,""";""", > shell=True) > #os.startfile('csoundgrid2.py', filename, > """;""") > finally: > dlg.Destroy() > > https://sourceforge.net/project/showfiles.php?group_id=156455 > http://www.dexrow.com From fredrik at pythonware.com Thu Nov 16 03:09:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 09:09:49 +0100 Subject: Secure Python In-Reply-To: <455c1665@quokka.wn.com.au> References: <455c1665@quokka.wn.com.au> Message-ID: timmy wrote: > congraulations you have discovered loops and their misuse if you don't know what the phrase "denial of service attack" means, you can always google for it. From bootiack at yahoo.com Thu Nov 9 19:44:40 2006 From: bootiack at yahoo.com (gavino) Date: 9 Nov 2006 16:44:40 -0800 Subject: how is python not the same as java? Message-ID: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> both are interpreted oo langauges...... From rvernica at gmail.com Fri Nov 17 18:42:12 2006 From: rvernica at gmail.com (Rares Vernica) Date: Fri, 17 Nov 2006 15:42:12 -0800 Subject: remove a list from a list In-Reply-To: References: <455E0046.1090005@tim.thechases.com> <455E0A20.9000509@tim.thechases.com> <455E100D.8030100@tim.thechases.com> Message-ID: This solution I think is pretty nice: source[:] = [x for x in source if x.lower() not in target] Thanks a lot for all the answers, Ray Steven D'Aprano wrote: > On Fri, 17 Nov 2006 12:00:46 -0800, Rares Vernica wrote: > >> Problem context: >> >> import os >> dirs_exclude = set(('a', 'b', 'e')) >> for root, dirs, files in os.walk('python/Lib/email'): >> # Task: >> # delete from "dirs" the directory names from "dirs_exclude" >> # case-insensitive >> >> The solution so far is: >> >> for i in xrange(len(dirs), 0, -1): >> if dirs[i-1].lower() in dirs_exclude: >> del dirs[i-1] >> >> I am looking for a nicer solution. > > Define "nicer". > > First thing I'd do is change the loop: > > for i in xrange(len(dirs)-1, -1, -1): > if dirs[i].lower() in dirs_exclude: > del dirs[i] > > Second thing I'd do is encapsulate it in a function instead of calling it > in place: > > def remove_in_place(source, target): > for i in xrange(len(source)-1, -1, -1): > if source[i].lower() in target: > del source[i] > > Third thing I'd do is replace the delete-in-place code away, and build a > new list using the set idiom, finally using list slicing to change the > source in place: > > def remove_in_place2(source, target): > target = set(s.lower() for s in target) > source[:] = [x for x in source if x.lower() not in target] > # note the assignment to a slice > > And finally, I would test the two versions remove_in_place and > remove_in_place2 to see which is faster. > > > import timeit > > setup = """from __main__ import remove_in_place > target = list("aEIOu") > source = list("AbcdEfghIjklmnOpqrstUvwxyz") > """ > > tester = """tmplist = source[:] # make a copy of the list! > remove_in_place(tmplist, target) > """ > > timeit.Timer(tester, setup).timer() > > You have to make a copy of the list on every iteration because you are > changing it in place; otherwise you change the values you are testing > against, and the second iteration onwards doesn't have to remove anything. > > > (All code above untested. Use at own risk.) > From vinjvinj at gmail.com Sun Nov 5 01:41:39 2006 From: vinjvinj at gmail.com (vj) Date: 4 Nov 2006 22:41:39 -0800 Subject: wing ide vs. komodo? In-Reply-To: <1162690929.501897.258360@b28g2000cwb.googlegroups.com> References: <2nRXg.108$1n3.2866@news.tufts.edu> <1162690929.501897.258360@b28g2000cwb.googlegroups.com> Message-ID: <1162708898.962171.161120@e3g2000cwe.googlegroups.com> Forgot to mention WING's file search and replace is pretty cool and powerful. It keeps checking changes in a different thread. If you want to change yyy in say 100 files you would: 1. specify yyy in the search window 2. A list of files get displayed with matching yyy 3. As you fix replace yyy in the files the list of files with matching yyy reduces automatically. This is very cool and very useful. Another thing I like about WING is that it warns you if you have tabs ans spaces mixed in a file. The embedded python shell is also a useful feature. VJ From vedran at v-programs.com Tue Nov 7 11:06:38 2006 From: vedran at v-programs.com (vedran at v-programs.com) Date: 7 Nov 2006 08:06:38 -0800 Subject: ftplib security support Message-ID: <1162915598.902958.91930@k70g2000cwa.googlegroups.com> Hello, One simple question.Which security ftplib support,and how to I 'load' these security to ftputil. (Please don't give me security modules) e.g. ftp=FTPHost('myhost','myusername','mypassword',session_factory=ftplib.FTP) is this example well? (for loading ftplib security to ftputil) Thanks From __peter__ at web.de Thu Nov 2 15:54:11 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Nov 2006 21:54:11 +0100 Subject: __doc__ in compiled script References: Message-ID: Gabriel Genellina wrote: > Hello > > I have a script starting with a docstring. After compiling it with > compile(), is there any way I could get the docstring? __doc__ on the > code object doesn't work. > I can't use __import__ because the script has top-level statements > that have to be executed only once (it's not supposed to be used as a > module). > > --- begin test.py --- > body = """ > "This is a docstring" > > x=0 > some(code).toBeExecuted("later") > """ > > co = compile(body,'','exec') > print co.__doc__ > > # what can I use for "something" below: ? > assert something(co)=="This is a docstring" > --- end test.py --- >>> co.co_consts[list(co.co_names).index("__doc__")] 'This is a docstring' or probably just >>> co.co_consts[0] 'This is a docstring' as I cannot imaginge the docstring to have a non-zero index. Peter From hg at nospam.com Tue Nov 28 13:24:32 2006 From: hg at nospam.com (hg) Date: Tue, 28 Nov 2006 12:24:32 -0600 Subject: pyxpcom In-Reply-To: References: Message-ID: Trent Mick wrote: > hg wrote: >> Hi, >> >> Can one tell me what the status of this project is ?. I did google ... >> but not much out there. > > PyXPCOM source is in the main Mozilla CVS tree. It is being maintained > by Mark Hammond (the original developer of the extension). There isn't a > lot of activity on it, I think, because: > 1. Mark did such a good job of implementing it the first time around > that it needs very little work :) > 2. It is very high learning curve to get into playing with PyXPCOM > because there are no conveniently packaged builds of PyXPCOM for current > (or any) versions of Firefox or Mozilla. > > Interestingly, Mark is currently working *full* support for Python in > the Mozilla code base, i.e. being able to use Python anywhere you can > currently use JavaScript (in > > > > it seems IEC is able to capture only the part. > I need to parse the string inside the tag it seems IEC is able to capture only the part. I need to parse the string inside the tag We really can't do anything with that. The url is useless because it's not absolute, so we can't look at your code. Please post a working link if you want help. Thanks, David From researchbase at gmail.com Thu Nov 16 13:11:36 2006 From: researchbase at gmail.com (krishnakant Mane) Date: Thu, 16 Nov 2006 23:41:36 +0530 Subject: how to print pdf with python on a inkjet printer. Message-ID: hello all. I am developing an ncurses based python application that will require to create pdf reports for printing. I am not using py--qt or wx python. it is a consol based ui application and I need to make a pdf report and also send it to a lazer or ink jet printer. is it possible to do so with python? or is it that I will have to use the wxpython library asuming that there is a print dialog which can open up the list of printers? if wx python and gui is the only way then it is ok but I will like to keep this application on the ncurses side. thanks. Krishnakant. From gagsl-py at yahoo.com.ar Tue Nov 14 14:34:56 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 14 Nov 2006 16:34:56 -0300 Subject: __cmp__ between dissimilar objects In-Reply-To: <1163522471.707278.178600@e3g2000cwe.googlegroups.com> References: <1163464397.679361.215050@m7g2000cwm.googlegroups.com> <1163522471.707278.178600@e3g2000cwe.googlegroups.com> Message-ID: <7.0.1.0.0.20061114163435.01d584b8@yahoo.com.ar> At Tuesday 14/11/2006 13:41, insyte at gmail.com wrote: > > When the rich comparison methods raise NotImplementedError, the > > comparison logic inside the interpreter tries reversing the operands. > >Can you point me to a description of this algorithm? It doesn't seem >to be described in the documentation for the rich comparison or __cmp__ >methods... PEP 207 http://www.python.org/dev/peps/pep-0207/ -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From __peter__ at web.de Thu Nov 16 05:39:57 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Nov 2006 11:39:57 +0100 Subject: split CSV fields References: Message-ID: robert wrote: > What is a most simple expression for splitting a CSV line with "-protected > fields? > > s='"123","a,b,\"c\"",5.640' >>> import csv >>> class mydialect(csv.excel): ... escapechar = "\\" ... >>> csv.reader(['"123","a,b,\\"c\\"",5.640'], dialect=mydialect).next() ['123', 'a,b,"c"', '5.640'] Peter From e0427417 at student.tuwien.ac.at Sun Nov 26 18:25:52 2006 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Mon, 27 Nov 2006 00:25:52 +0100 Subject: Generator question In-Reply-To: References: Message-ID: <456a2204$0$11868$3b214f66@tunews.univie.ac.at> Robert Kern wrote: > Timothy Wu wrote: >> Hi, >> >> Using generator recursively is not doing what I expect: >> >> def test_gen(x): >> yield x >> x = x - 1 >> if x != 0: >> test_gen(x) > > The only thing that the last line does is *create* a new generator object. You > need to actually iterate over it and yield its values. E.g. > > > In [2]: def test_gen(x): > ...: yield x > ...: x -= 1 > ...: if x != 0: > ...: for y in test_gen(x): > ...: yield y > ...: > ...: > > In [3]: list(test_gen(3)) > Out[3]: [3, 2, 1] > > why not this? def test_gen(x): for y in xrange(x,0,-1): yield y or even better/shorter: test_gen = lambda x: xrange(x,0,-1) From fredrik at pythonware.com Sun Nov 19 05:35:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Nov 2006 11:35:26 +0100 Subject: Why isn't SPLIT splitting my strings In-Reply-To: <1163931285.390782.130500@h54g2000cwb.googlegroups.com> References: <1163931285.390782.130500@h54g2000cwb.googlegroups.com> Message-ID: ronrsr wrote: > I'm trying to break up the result tuple into keyword phrases. The > keyword phrases are separated by a ; -- the split function is not > working the way I believe it should be. >>> help(str.split) split(...) S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string. note that it says *delimiter string*, not *list of characters that I want it to split on*. From no-spam at no-spam-no-spam.com Thu Nov 2 13:32:54 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 02 Nov 2006 19:32:54 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? Message-ID: I'd like to use multiple CPU cores for selected time consuming Python computations (incl. numpy/scipy) in a frictionless manner. Interprocess communication is tedious and out of question, so I thought about simply using a more Python interpreter instances (Py_NewInterpreter) with extra GIL in the same process. I expect to be able to directly push around Python Object-Trees between the 2 (or more) interpreters by doing some careful locking. Any hope to come through? If possible, what are the main dangers? Is there an example / guideline around for that task? - using ctypes or so. Or is there even a ready made Python module which makes it easy to setup and deal with extra Interpreter instances? If not, would it be an idea to create such thing in the Python std libs to make Python multi-processor-ready. I guess Python will always have a GIL - otherwise it would loose lots of comfort in threaded programming robert From gagsl-py at yahoo.com.ar Thu Nov 16 20:59:54 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 16 Nov 2006 22:59:54 -0300 Subject: Writing to Registry In-Reply-To: References: Message-ID: <7.0.1.0.0.20061116225853.03fcf890@yahoo.com.ar> At Thursday 16/11/2006 21:39, Samantha wrote: > > http://docs.python.org/lib/module--winreg.html#l2h-5827 >Thanks for the link. Notice that surely you already have the full Python documentation, it comes with the standard distribution. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From moonbee5555555555 at yahoo.com Thu Nov 30 16:00:47 2006 From: moonbee5555555555 at yahoo.com (Boneh) Date: 30 Nov 2006 13:00:47 -0800 Subject: How can I change the icon Message-ID: <1164920447.562855.159040@h54g2000cwb.googlegroups.com> Is it possible to change the icon "Tk" of the windows popped up ? From ratchetgrid at googlemail.com Sat Nov 25 17:30:49 2006 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Sat, 25 Nov 2006 22:30:49 +0000 Subject: Graph Data Structures In-Reply-To: <1164483939.464327.143450@f16g2000cwb.googlegroups.com> References: <1164465588.399198.173830@f16g2000cwb.googlegroups.com> <1164483939.464327.143450@f16g2000cwb.googlegroups.com> Message-ID: <676224240611251430s6b938db2jd7ee59abd5eef0e8@mail.gmail.com> > > https://networkx.lanl.gov/ This was working for me earlier, I managed to get everything from there earlier. It seems a very good package. It seems theres more out there than what I had thought, which unfortunately makes it harder for me to decide what to use (pynetwork and bgl look useful aswell). I m going to do some testing on it later and see what happens with it. Thanks a lot for your help. Has anyone got an idea how I could split the contents of a node and its representation (to save memory in my graph). ie.... the nodes contain the start and end coordinates and id and the actual representation contains the string. I was going to have : class Node(object): pass class Section(Node): pass class Item(object): pass Where section contains a slice of the Item which im interested. I m just not sure how I can access the contents of item without storing it. ---> If u get what I mean??? Many Thanks in advance Nathan From jibalamy at free.fr Sun Nov 26 13:34:56 2006 From: jibalamy at free.fr (Jiba) Date: Sun, 26 Nov 2006 19:34:56 +0100 Subject: acessing to the raw data of an email message Message-ID: <20061126193456.2bb5d97a@autremonde> Hi, I'm using the email Python package for parsing mail and checking GPG signature. The Message object doesn't store the raw message data. Message.as_string "rebuild" the whole message, for example it may gives: Content-Disposition: attachment; filename=text.txt whereas the original message was containing: Content-Disposition: attachment; filename=text.txt From the RFC point of view, both are equivalent. However, when checking the signature using GPG, there are not the same for GPG, and thus the check fails. Does anyone have an idea ? I think it would be nice to let the parser add the raw message data in the Message object. Thanks, Jiba From ptmcg at austin.rr._bogus_.com Wed Nov 22 16:42:26 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 22 Nov 2006 21:42:26 GMT Subject: PyParsing and Headaches References: <1164223072.219676.157790@j44g2000cwa.googlegroups.com> Message-ID: <6v39h.2422$Gk5.2255@tornado.texas.rr.com> "Bytter" wrote in message news:1164223072.219676.157790 at j44g2000cwa.googlegroups.com... > Hi, > > I'm trying to construct a parser, but I'm stuck with some basic > stuff... For example, I want to match the following: > > letter = "A"..."Z" | "a"..."z" > literal = letter+ > include_bool := "+" | "-" > term = [include_bool] literal > > So I defined this as: > > literal = Word(alphas) > include_bool = Optional(oneOf("+ -")) > term = include_bool + literal > > The problem is that: > > term.parseString("+a") -> (['+', 'a'], {}) # OK > term.parseString("+ a") -> (['+', 'a'], {}) # KO. It shouldn't > recognize any token since I didn't said the SPACE was allowed between > include_bool and literal. > As Chris pointed out in his post, the most direct way to fix this is to use Combine. Note that Combine does two things: it requires the expressions to be adjacent, and it combines the results into a single token. For instance, when defining the expression for a real number, something like: realnum = Optional(oneOf("+ -")) + Word(nums) + "." + Word(nums) Pyparsing would parse "3.14159" into the separate tokens ['', '3', '.', '14159']. For this grammar, pyparsing would also accept "2. 23" as ['', '2', '.', '23'], even though there is a space between the decimal point and "23". But by wrapping it inside Combine, as in: realnum = Combine(Optional(oneOf("+ -")) + Word(nums) + "." + Word(nums)) we accomplish two things: pyparsing only matches if all the elements are adjacent, with no whitespace or comments; and the matched token is returned as ['3.14159']. (Yes, I left off scientific notation, but it is an extension of the same issue.) Pyparsing in general does implicit whitespace skipping; it is part of the zen of pyparsing, and distinguishes it from conventional regexps (although I think there is a new '?' switch for re's that puts '\s*'s between re terms for you). This is to simplify the grammar definition, so that it doesn't need to be littered with "optional whitespace or comments could go here" expressions; instead, whitespace and comments (or "ignorables" in pyparsing terminology) are parsed over before every grammar expression. I instituted this out of recoil from a previous project, in which a co-developer implemented a boolean parser by first tokenizing by whitespace, then parsing out the tokens. Unfortunately, this meant that "color=='blue' && size=='medium'" would not parse successfully, instead requiring "color == 'blue' && size == 'medium'". It doesn't seem like much, but our support guys got many calls asking why the boolean clauses weren't matching. I decided that when I wrote a parser, "y=m*x+b" would be just as parseable as "y = m * x + b". For that matter, you'd be surprised where whitespace and comments sneak in to people's source code: spaces after left parentheses and comments after semicolons, for example, are easily forgotten when spec'ing out the syntax for a C "for" statement; whitespace inside HTML tags is another unanticipated surprise. So looking at your grammar, you say you don't want to have this be a successful parse: term.parseString("+ a") -> (['+', 'a'], {}) because, "It shouldn't recognize any token since I didn't said the SPACE was allowed between include_bool and literal." In fact, pyparsing allows spaces by default, that's why the given parse succeeds. I would turn this question around, and ask you in terms of your grammar - what SHOULD be allowed between include_bool and literal? If spaces are not a problem, then your grammar as-is is sufficient. If spaces are absolutely verboten, then there are 2 or 3 different techniques in pyparsing to disable the whitespace-skipping behavior, depending on whether you want all whitespace skipping disabled, just for literals of a certain type, or just for literals when following a leading include_bool sign. Thanks for giving pyparsing a try; if you want further help, you can post here, or on the pyparsing wiki - the discussion threads on the Home page are a pretty good support and message log. -- Paul From bytter at gmail.com Thu Nov 23 10:30:48 2006 From: bytter at gmail.com (Bytter) Date: 23 Nov 2006 07:30:48 -0800 Subject: PyParsing and Headaches In-Reply-To: <1164283023.996975.292750@f16g2000cwb.googlegroups.com> References: <1164223072.219676.157790@j44g2000cwa.googlegroups.com> <1164283023.996975.292750@f16g2000cwb.googlegroups.com> Message-ID: <1164295848.442041.89560@k70g2000cwa.googlegroups.com> Heya there, Ok, found the solution. I just needed to use leaveWhiteSpace() in the places I want pyparsing to take into consideration the spaces. Thx for the help. Cheers! Hugo Ferreira On Nov 23, 11:57 am, "Bytter" wrote: > (This message has already been sent to the mailing-list, but I don't > have sure this is arriving well since it doesn't come up in the usenet, > so I'm posting it through here now.) > > Chris, > > Thanks for your quick answer. That changes a lot of stuff, and now I'm > able to do my parsing as I intended to. > > Still, there's a remaining problem. By using Combine(), everything is > interpreted as a single token. Though what I need is that > 'include_bool' and 'literal' be parsed as separated tokens, though > without a space in the middle... > > Paul, > > Thanks for your detailed explanation. One of the things I think is > missing from the documentation (or that I couldn't find easy) is the > kind of explanation you give about 'The Way of PyParsing'. For example, > It took me a while to understand that I could easily implement simple > recursions using OneOrMany(Group()). Or maybe things were out there and > I didn't searched enough... > > Still, fwiw, congratulations for the library. PyParsing allowed me to > do in just a couple of hours, including learning about it's API (minus > this little inconvenient) what would have taken me a couple of days > with, for example, ANTLR (in fact, I've already put aside ANTLR more > than once in the past for a built-from-scratch parser). > > Cheers, > > Hugo Ferreira > > On Nov 22, 7:50 pm, Chris Lambacher wrote: > > > On Wed, Nov 22, 2006 at 11:17:52AM -0800, Bytter wrote: > > > Hi, > > > > I'm trying to construct a parser, but I'm stuck with some basic > > > stuff... For example, I want to match the following: > > > > letter = "A"..."Z" | "a"..."z" > > > literal = letter+ > > > include_bool := "+" | "-" > > > term = [include_bool] literal > > > > So I defined this as: > > > > literal = Word(alphas) > > > include_bool = Optional(oneOf("+ -")) > > > term = include_bool + literal+ here means that you allow a space. You need to explicitly override this. > > Try: > > > term = Combine(include_bool + literal) > > > > The problem is that: > > > > term.parseString("+a") -> (['+', 'a'], {}) # OK > > > term.parseString("+ a") -> (['+', 'a'], {}) # KO. It shouldn't > > > recognize any token since I didn't said the SPACE was allowed between > > > include_bool and literal. > > > > Can anyone give me an hand here? > > > > Cheers! > > > > Hugo Ferreira > > > > BTW, the following is the complete grammar I'm trying to implement with > > > pyparsing: > > > > ## L ::= expr | expr L > > > ## expr ::= term | binary_expr > > > ## binary_expr ::= term " " binary_op " " term > > > ## binary_op ::= "*" | "OR" | "AND" > > > ## include_bool ::= "+" | "-" > > > ## term ::= ([include_bool] [modifier ":"] (literal | range)) | ("~" > > > literal) > > > ## modifier ::= (letter | "_")+ > > > ## literal ::= word | quoted_words > > > ## quoted_words ::= '"' word (" " word)* '"' > > > ## word ::= (letter | digit | "_")+ > > > ## number ::= digit+ > > > ## range ::= number (".." | "...") number > > > ## letter ::= "A"..."Z" | "a"..."z" > > > ## digit ::= "0"..."9" > > > > And this is where I got so far: > > > > word = Word(nums + alphas + "_") > > > binary_op = oneOf("* and or", caseless=True).setResultsName("operator") > > > include_bool = oneOf("+ -") > > > literal = (word | quotedString).setResultsName("literal") > > > modifier = Word(alphas + "_") > > > rng = Word(nums) + (Literal("..") | Literal("...")) + Word(nums) > > > term = ((Optional(include_bool) + Optional(modifier + ":") + (literal | > > > rng)) | ("~" + literal)).setResultsName("Term") > > > binary_expr = (term + binary_op + term).setResultsName("binary") > > > expr = (binary_expr | term).setResultsName("Expr") > > > L = OneOrMore(expr) > > > > -- > > > GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list From garylinux at gmail.com Wed Nov 22 20:09:27 2006 From: garylinux at gmail.com (garylinux at gmail.com) Date: 22 Nov 2006 17:09:27 -0800 Subject: The Python Papers Edition One In-Reply-To: <1164156093.359433.315790@e3g2000cwe.googlegroups.com> References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <1164106267.882164.124670@h48g2000cwc.googlegroups.com> <1164156093.359433.315790@e3g2000cwe.googlegroups.com> Message-ID: <1164244166.988532.261370@l39g2000cwd.googlegroups.com> Tell us about it again when it is available as html. We will be glad to read it. I am sorry but I almost never find a pdf worth the bother of clicking on it. Sorry From steve at REMOVE.THIS.cybersource.com.au Sat Nov 25 18:16:02 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 26 Nov 2006 10:16:02 +1100 Subject: a -very- case sensitive search References: <1164490795.866046.133230@45g2000cws.googlegroups.com> Message-ID: On Sat, 25 Nov 2006 13:39:55 -0800, Ola K wrote: > Hi, > I am pretty new to Python and I want to make a script that will search > for the following options: > 1) words made of uppercase characters -only- (like "YES") > 2) words made of lowercase character -only- (like "yes") > 3) and words with only the first letter capitalized (like "Yes") > * and I need to do all these considering the fact that not all letters > are indeed English letters. > > I went through different documention section but couldn't find a right > condition, function or method for it. At the command prompt: >>> dir('') # result edited for clarity [ ... 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', ... ] Then do this: >>> help(''.islower) and read the text it provides. Then experiment on the command line: >>> 'abcd1234'.islower() True >>> 'aBcd1234'.islower() False Then come back to us if they aren't suitable, and tell us WHY they aren't suitable. -- Steven. From pavlovevidence at gmail.com Thu Nov 30 09:25:40 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 30 Nov 2006 06:25:40 -0800 Subject: More elegant to get a name: o.__class__.__name__ In-Reply-To: References: Message-ID: <1164896740.696013.5390@j72g2000cwa.googlegroups.com> alf wrote: > Hi, > is there a more elegant way to get o.__class__.__name__. For instance I > would imagine name(o). def name_of_type(o): return o.__class__.__name__ name_of_type(o) Carl Banks P.S. name(o) suggests it's the name of the object, not the type P.P.S. you could use type(o).__name__ but it doesn't work for old-style classes From sylvain.thenault at logilab.fr Thu Nov 23 10:45:35 2006 From: sylvain.thenault at logilab.fr (Sylvain =?iso-8859-1?Q?Th=E9nault?=) Date: Thu, 23 Nov 2006 16:45:35 +0100 Subject: [ANN] pylint 0.12.2 / astng 0.16.3 Message-ID: <20061123154535.GB21319@crater.logilab.fr> Hi there ! I'm pleased to announce new bugs fix releases of pylint and astng. Most bug discussed more or less recently on the python-projects mailing list should be fixed by those releases, and astng inference capability has been enhanced for some construction, so upgrade is recommended. Visit the respective projects'page of our fresh new .org site to get the latest source distribution :o) http://www.logilab.org/project/name/pylint http://www.logilab.org/project/name/logilab-astng Enjoy ! -- Sylvain Th?nault LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From dlenski at gmail.com Mon Nov 13 17:33:10 2006 From: dlenski at gmail.com (Dan Lenski) Date: 13 Nov 2006 14:33:10 -0800 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <45538b0d$0$26485$c3e8da3@news.astraweb.com> <4558b437$0$32430$c3e8da3@news.astraweb.com> Message-ID: <1163457190.758583.76570@h48g2000cwc.googlegroups.com> Ben Finney wrote: > Readability doesn't vary directly or inversely with the number of > characters, even though it is affected when they change. Good point! Perl has more characters than Python, and I find they make it harder to read because they are distracting. Brainf*** (http://en.wikipedia.org/wiki/Brainf***) only has 8 possible characters, and it's hard to read because you can't easily recognize repeating patterns or features. I think this is something that typographers have been studying for hundreds of years, how changing the shape of characters, page layout, and typographical conventions affect the ability to easily read and comprehend text. I know that in college I hated one physics textbook which used monospaced fonts... it was well-written but just hurt my eyes to browse through. Dan From scott.daniels at acm.org Sat Nov 25 21:03:37 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 25 Nov 2006 18:03:37 -0800 Subject: Local variables persist in functions? In-Reply-To: <1164355869.607182.278200@l12g2000cwl.googlegroups.com> References: <1164355869.607182.278200@l12g2000cwl.googlegroups.com> Message-ID: <4568ec90$1@nntp0.pdx.net> 120psi at gmail.com wrote: > I'm a bit baffled. Here is a bit of fairly straightforward code: > > def _chunkify( l, chunkSize, _curList = list() ): ... > _chunkify simply breaks a sequence into a sequence of smaller lists of > size <= chunkSize. The first call works fine, but if I call it > multiple times, weirdness happens. > > Considering the default value of _curList, these statements should be > identical. Any pointers? Did I miss something in the python reference > manual? (running 2.4.3, fyi) You've already got the real answer. How about considering iterators, since I presume you are chunking to help some kind of processing.: def chunky(src, size): '''Produce a (possibly long source) in size-chunks or less.''' assert size > 0 for start in range(0, len(src), size): yield src[start : start + size] def chunkify(alist, size, _curList=None): if _curList is None: return list(chunky(alist, size)) _curList.extend(list(chunky(alist, size))) return _curList I suspect most often you can use chunky directly: for chunk in chunky(somedata, size): ... for size in range(1, 30): print size, list(chunky('abcdefghijklmnopqrstuvwxyz', size)) --Scott David Daniels scott.daniels at acm.org From bearophileHUGS at lycos.com Wed Nov 22 19:45:38 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Nov 2006 16:45:38 -0800 Subject: Abelson and Python In-Reply-To: <1164242138.749183.144160@k70g2000cwa.googlegroups.com> References: <1164239517.067445.179320@e3g2000cwe.googlegroups.com> <1164240649.628193.65300@f16g2000cwb.googlegroups.com> <1164241247.453138.296580@m73g2000cwd.googlegroups.com> <1164242138.749183.144160@k70g2000cwa.googlegroups.com> Message-ID: <1164242738.395574.94350@h54g2000cwb.googlegroups.com> mensanator at aol.com: > Haven't heard of that one, although I've got DrScheme. Right, sorry, I meant that one :-) > I find that hierarchy extremely annoying. I don't see the need for it. > I never use OOP in Python yet there's no need for me to have a > stripped down version, I just don't use it. But Python too contains some things that can bite a newbie of the language. (BTW, in some situations I too have had to access to the full Scheme language, so you may be partially right). > But those are implementation details, which you can't avoid. > A bad implementation spoils a language even if the language itself > is fabulous. And a good implementation like DrScheme makes the Scheme language usable too :-) Bye, bearophile From jordan.taylor2 at gmail.com Tue Nov 14 14:20:54 2006 From: jordan.taylor2 at gmail.com (Jordan) Date: 14 Nov 2006 11:20:54 -0800 Subject: Python development time is faster. In-Reply-To: References: <1163425734.640509.99420@m73g2000cwd.googlegroups.com> Message-ID: <1163532054.236735.326240@h48g2000cwc.googlegroups.com> Just a little something I realized after writing the same program in C++ and python (a simple chat client and server, with one on one and chat room capabilities). I used wxwidgets and wxpython respectively for the GUIs, and they weren't extremely elaborate, just some basic functionality, a few frames, a few buttons, added a few sound options... nothing huge ;D However, making the gui for python took me less than a fourth of the time it took to make the equivalent (the C++ one was actually a bit worse, there were some things that were implemented in wxpython that just didn't want to work in wxwidgets). I'm not saying that coding in python is going to let you develop things 4 times faster, but there are some obvious advantages that I think greatly increase development rate. Just making the framework for the C++ gui was very time consuming. Added to this is that python doesn't require linking and specifying libraries and all the other things that tend to go wrong on the first attempt at compiling something. You also don't have to specify void, int, char etc for functions, and of course, there's no pointers. :D Best thing you can do is probably just to download python and tinker with it, maybe try making some python equivalents to whatever you've made in other languages. Cheers -Jordan Hendrik van Rooyen wrote: > "Chris Brat" wrote: > > > > I've seen a few posts, columns and articles which state that one of the > > advantages of Python is that code can be developed x times faster than > > languages such as <>. > > > > Does anyone have any comments on that statement from personal > > experience? > > How is this comparison measured? > > I don't think it can be, objectively - comparing two teams, one using language > "a", and the other python, to do a task, is simply comparing the skill levels > of the two teams - and using the same team to do the same task in two different > languages is also misleading, because of the experience gained in the first > iteration. > > Python is actually astonishing - it seems to "fit the brain" of a large number > of people - it is very easy to get started with, and is rich enough to keep > surprising you - even after considerable time hacking around with it. > It can do OO, but you can also write procedures in it, and you can even mix the > two in the same module, and most of the time it "just works" - and when it > doesn't, it is normally very easy to teach yourself what you are doing wrong by > playing at the interactive interpreter prompt. This makes for productivity, as > you can write quite complex things in a day or so, from scratch, such as: > > A single pass "assembler" for a virtual machine with 33 instructions - from > nothing to running, fully debugged, in two days. > > A simple sliding window protocol - coded up from nothing in four days - mostly > spent staring into space, imagining problems, instead of coding... so the > "design" time is included... but its not working yet, as I have to write the > other side in assembler on a very small machine, which would normally have taken > me almost a month, but that will now probably take about two weeks, as I have > the Python code to translate... > > And I am not a guru on this group, and I have just idly mucked around with > Python for about a year in real time, not doing it full time, or making any real > effort to study the language formally beyond lurking here - there are other > people here on this group who, I am sure, could beat the hell out of these > times, both for the design and the coding. > > So to sum up my personal perspective - it is very worth while to know a little > python, even if you just use it as a prototyping language - it gets you going > rapidly... > > - Hendrik From sjmachin at lexicon.net Mon Nov 20 05:23:38 2006 From: sjmachin at lexicon.net (John Machin) Date: 20 Nov 2006 02:23:38 -0800 Subject: fileinput.input('test.txt') => ERROR: input() already active In-Reply-To: <1164016727.678036.225640@e3g2000cwe.googlegroups.com> References: <1164011174.630226.91580@j44g2000cwa.googlegroups.com> <1164016727.678036.225640@e3g2000cwe.googlegroups.com> Message-ID: <1164018218.422003.286870@h54g2000cwb.googlegroups.com> cyberco wrote: > Ah, thanks! > Another related question I have: The following piece edits in place, > but ads whitelines between all lines of a Windows text file. Why? > > =========================== > fi = fileinput.input('test.txt', inplace=1) > for l in fi: Please don't use lowercase "L" as a variable name; it is too easily confused with the digit 1 in some fonts. Use meaningful names. > print l.replace('a', 'b') > =========================== fi = fileinput.input('test.txt', inplace=1) for line in fi: print line.replace('a', 'b') It's nothing to do with whether the file is a "Windows text file" or not. The reason is that line already has a "\n" i.e. newline character at the end. The print statement adds another. Either: (1) change print blahblah to print blahblah, # comma suppresses the added newline or (2) put import sys up the front and change print blahblah to sys.stdout.write(blahblah) HTH, John From fredrik at pythonware.com Wed Nov 1 08:31:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 01 Nov 2006 14:31:51 +0100 Subject: Why can't you assign to a list in a loop without enumerate? In-Reply-To: <4qrln8Fo2ollU1@individual.net> References: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> <4qrln8Fo2ollU1@individual.net> Message-ID: Bjoern Schliessmann wrote: >> what's wrong with using enumerate? or a list comprehension? or >> some other of the many different ways you can use to build a list >> from a set of values? > > Shouldn't there be one -- and preferably only one -- obvious way to > do it? 8) > > Python Cookbook says "enumerate()", is this still correct with 2.5? define "it". From hg at nospam.com Thu Nov 23 10:30:53 2006 From: hg at nospam.com (hg) Date: Thu, 23 Nov 2006 09:30:53 -0600 Subject: Simple threading In-Reply-To: <1164295697.757788.26710@e3g2000cwe.googlegroups.com> References: <1164295697.757788.26710@e3g2000cwe.googlegroups.com> Message-ID: <4565BEAD.7080206@nospam.com> jrpfinch wrote: > I'm just getting started on threading and was wondering why the > following code does not work (i know globals is bad style - I'll > eliminate them eventually). All I get is a blank cursor flashing. > > Many thanks > > Jon > > import threading > import sys > import time > global g_datum > global g_rawfile > global g_rawtext > global g_overs > global g_currentover > global g_secondspertick > > > g_secondspertick=5 > g_datum=time.time() > g_currenttick=1 > g_rawfile=open('inputashes.txt','r') > g_rawtext=g_rawfile.read() > g_overs=g_rawtext.split('

') > g_currentover=0 > > > class ImapThread(threading.Thread): > def run(self): > global g_currenttick > if time.time() > (g_datum + (g_secondspertick * > g_currenttick)): > print "Ticked %s" % g_currenttick > g_currenttick=g_currenttick+1 > print g_currenttick > sys.stdout.flush() > time.sleep(0.01) > > def main(): > ImapThread().start() > while 1: > pass > > if __name__ == "__main__": > main() > Run gets called only once: you need to put your logic in a "while True" or something equivalent/define some escape clause. Right now you just get into the implicit "else" and get out. hg import time global g_datum global g_rawfile global g_rawtext global g_overs global g_currentover global g_secondspertick g_secondspertick=5 g_datum=time.time() g_currenttick=1 #g_rawfile=open('inputashes.txt','r') #g_rawtext=g_rawfile.read() #g_overs=g_rawtext.split('

') g_currentover=0 class ImapThread(threading.Thread): def run(self): while True: global g_currenttick if time.time() > (g_datum + (g_secondspertick * g_currenttick)): print "Ticked %s" % g_currenttick g_currenttick=g_currenttick+1 print g_currenttick sys.stdout.flush() else: print 'HERE' time.sleep(0.01) def main(): ImapThread().start() while 1: pass if __name__ == "__main__": main() From martin at v.loewis.de Sun Nov 26 04:09:34 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 26 Nov 2006 10:09:34 +0100 Subject: who is maintainer of xml-rpc module? In-Reply-To: References: Message-ID: <456959CE.3000206@v.loewis.de> Mark Harrison schrieb: > So, I've made a couple of small but useful additions to > the xml-rpc package. Is there an assigned maintainer > of the package I should communicate with? The author of the module is Fredrik Lundh; you can try to contact him. If you want to contribute your changes to the Python project, you should follow the procedure at http://www.python.org/dev/patches/ Consider filling out a contribution form also in this case: http://www.python.org/psf/contrib/ > I'd like to get these into wider circulation if possible... > what's the best way to do this? Depends on how the source is structured. If it is a separate set of modules, you should package them as a distutils package, and upload them to the cheeseshop (cheeseshop.python.org). If they are just patches to the existing modules, you can still upload them to the cheeseshop. In either case, you can then send an announcement to comp.lang.python.announce that you made them available. Regards, Martin From mgiann at beta-cae.gr Sun Nov 26 11:04:54 2006 From: mgiann at beta-cae.gr (Michalis Giannakidis) Date: Sun, 26 Nov 2006 18:04:54 +0200 Subject: Inheritance from builtin list and override of methods. Message-ID: <200611261804.54669.mgiann@beta-cae.gr> Dear all I tried to override methods of build in Python types, so as to change their behavior. I tried to override list.__getitem__ list.__setitem__ and some others alike The test case is: #!/usr/bin/env python class L(list): def __getitem__(self, i): print 'G', i return list.__getitem__(self, i) def __setitem__(self, i, y): print 'S:', i, y return list.__setitem__(self, i, y) def __setslice__(self, i, j, y): print 'SL:', i, j, y return list.__setslice__(self, i, j, y) def __iter__(self, x): print 'iter:', x return list.__iter__(self, x) l = L() l.append(3) # this does not call my __setitem__ l.append(2) l.append(1) l[2] = 6 # this calls my __setitem__ l.sort(key=lambda x: x ) print l I expected that the call to l.sort() would call my versions of the list methods (iter, setitem etc ) but it didn't. Also the call to l.append didn't call my setitem but the assignment l[2] = 6 did! I expected my versions of iter, setitem, getitem to be called with the typical impementation of sorting from C in mind. Could someone please explain the reasoning/behabiour of these? Python Version: Python 2.4.2 (#1, May 26 2006, 14:35:35) [GCC 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)] on linux2 Thank you very much in advance. Michalis -- Michalis Giannakidis From goofy666 at scarlet.be Sat Nov 25 17:01:54 2006 From: goofy666 at scarlet.be (Goofy666) Date: Sat, 25 Nov 2006 23:01:54 +0100 Subject: a -very- case sensitive search In-Reply-To: <1164490795.866046.133230@45g2000cws.googlegroups.com> References: <1164490795.866046.133230@45g2000cws.googlegroups.com> Message-ID: Hi > * and I need to do all these considering the fact that not all letters > are indeed English letters. You mean letters from the English alphabet (derived from the Latin/Roman alphabet, fyi)? I'm sorry for the nitpicking, but 'English letters' sounds a bit too 'ackward' to me. > I went through different documention section but couldn't find a right > condition, function or method for it. > Suggestions will be very much appriciated... I'm still (trying to) learn(ing) it myself, but you can try looking into using regular expressions. There's a standard module for it (re), see the PyLib Reference for details; http://docs.python.org/lib/module-re.html. --Laurens Ola K wrote: > Hi, > I am pretty new to Python and I want to make a script that will search > for the following options: > 1) words made of uppercase characters -only- (like "YES") > 2) words made of lowercase character -only- (like "yes") > 3) and words with only the first letter capitalized (like "Yes") > * and I need to do all these considering the fact that not all letters > are indeed English letters. > > I went through different documention section but couldn't find a right > condition, function or method for it. > Suggestions will be very much appriciated... > --Ola > From matthew at agrip.org.uk Sun Nov 26 06:32:04 2006 From: matthew at agrip.org.uk (Matthew Tylee Atkinson) Date: Sun, 26 Nov 2006 11:32:04 +0000 (UTC) Subject: Oops! Message-ID: Apologies for any repeated posts, my 'net connection died unexpectedly! -- Matthew Tylee Atkinson From vincent.arnoux at rfo.atmel.com Wed Nov 29 11:23:48 2006 From: vincent.arnoux at rfo.atmel.com (Vincent Arnoux) Date: Wed, 29 Nov 2006 17:23:48 +0100 Subject: Reading GDSII layouts In-Reply-To: <1164732963.158392.35670@14g2000cws.googlegroups.com> References: <1164732963.158392.35670@14g2000cws.googlegroups.com> Message-ID: <200611291723.49468.vincent.arnoux@rfo.atmel.com> Le mardi 28 novembre 2006 17:56, Paddy a ?crit?: >> The link you gave states this near the top: > IPKISS is a python-based library for the generation of GDSII layouts, > including hierarchy. > It has grown out of the GDS_KEY library, but it is more flexible and > object oriented. Contrary > to GDS_KEY, **it can read and edit existing GDSII files**. > > And at the bottom of the page: > * Import of existing GDSII files into a layout (import.py) > > It looks to be a reader?! > > - Paddy. Yes, you are right, but I am actually looking for a library that would display only cell references, and not load the entire design (what will be too time consuning with Python). And this doesn't look to be present in IPKiss. Vincent From tuglyraisin at aol.com Wed Nov 15 11:22:02 2006 From: tuglyraisin at aol.com (Andrew Burton) Date: Wed, 15 Nov 2006 10:22:02 -0600 Subject: Python-2.5.exe? Message-ID: What Python is best for installing to a USB Drive? I've actually got 2.5 on a drive, but I forget which installation package I used. It seems to me that it was an EXE file, but I cannot seem to find one of those today. Can the Python-2.5.msi installation files from python.org be installed so as not to touch the registry, to make them portable? -- Andrew Burton tuglyraisin at aol.com http://utilitarian.us - A Guide to Esoteric Technology in Paragon City http://jarodrussell.livejournal.com/ - Take a guess. ;) From cginboston at hotmail.com Tue Nov 7 16:25:36 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Tue, 07 Nov 2006 21:25:36 GMT Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <7xk62ct5pf.fsf@ruckus.brouhaha.com> <1162913881.953664.254960@m73g2000cwd.googlegroups.com> <1162922230.992249.52430@f16g2000cwb.googlegroups.com> <4550cc64$0$3462$9b622d9e@news.freenet.de> <1162928970.223276.72600@h48g2000cwc.googlegroups.com> <4550F2AE.1010205@v.loewis.de> Message-ID: <4550FA2E.1070404@hotmail.com> Joe Seigh wrote: > Martin v. L?wis wrote: >> You still didn't say what you would suggest to make it thread-safe >> again; most likely, you proposal would be to add locking. If I >> understand Joe's approach correctly, he has a solution that does >> not involve locking (although I don't understand how it works). >> > Sun had applied for a patent on it. You can go to the > uspto search page here http://www.uspto.gov/patft/index.html > and look for > > 20060218561 Code preparation technique employing lock-free pointer > operations > 20060037026 Lightweight reference counting using single-target > synchronization > > Click on the images link on the patent application where the illustrations > are which show the concepts probably better than the text. > > The first one above is actually a continuation patent on three different > techniques. One using double wide compare and swap, one using ROP (Repeat > Offender Problem), a form of PDR, and one using DCAS (compare and swap > of two separate locations) which only exists on MC68020 and MC68030 > processors. > Check out the work in the '80s from the NYU Ultra project. They did a great deal of work on using atomic incr/decr for all sorts of algorithms to get around locking on parallel processors. Chaz. From robert.kern at gmail.com Fri Nov 17 13:42:11 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 17 Nov 2006 12:42:11 -0600 Subject: What python modules are available? In-Reply-To: <1163767023.599564.260920@m7g2000cwm.googlegroups.com> References: <1163765733.745577.116670@m73g2000cwd.googlegroups.com> <1163767023.599564.260920@m7g2000cwm.googlegroups.com> Message-ID: Why Tea wrote: > All I need is something to provide me with array features. I can't > remember why I chose to use numarray a while ago... You will probably want numpy these days. numarray is being phased out. http://numpy.scipy.org/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From daigno at gmail.com Tue Nov 28 20:39:03 2006 From: daigno at gmail.com (=?ISO-8859-1?Q?=C9ric_Daigneault?=) Date: Tue, 28 Nov 2006 20:39:03 -0500 Subject: why would anyone use python when java is there? Message-ID: <456CE4B7.6050402@gmail.com> > wtf a reasonable question... But before I run circle yelling "the trolls are here, the trolls are here" I got one for you... why would anyone use java when python is there?? ;-) .^_^. Eric :D, From python-url at phaseit.net Mon Nov 13 10:46:52 2006 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 13 Nov 2006 15:46:52 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 13) Message-ID: QOTW: "It is humbling to see how simple yet powerfull python`s view on things is...." - ??ric Daigneault http://groups.google.com/group/comp.lang.python/msg/bbd842715bb5b6eb "[I]f a machine is expected to be infallible, it cannot also be intelligent." - Alan Turing, 20 February 1947, lecture to London Mathematical Socity on ACE Stefan Schukat illustrates an instructive use of COM in a multi-threaded context which manages a MATLAB instance: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c13315f002ab025/ Someone should capture the scattered but valuable observations of this report on Windows-hosted extending into a more enduring document: http://groups.google.com/group/comp.lang.python/browse_frm/thread/36c13e238e6e3bb4 Paul Boddie provides references on concurrency in Python: http://groups.google.com/group/comp.lang.python/msg/4a507814e704b782 Microsoft publicizes IronPython's ASP.Net capabilities: http://www.infoworld.com/archives/emailPrint.jsp?R=printThis&A=/article/06/11/07/HNvsiron_1.html http://www.eweek.com/article2/0,1895,2053498,00.asp?kc=EWWHNEMNL110906EOAD The latest release of eric3 supports QScintilla autocompletion, and more: http://www.die-offenbachs.de/detlev/eric.html Is a "parameter-holding class" reasonable? Probably so, at least on occasion: http://groups.google.com/group/comp.lang.python/browse_thread/thread/64d84ae1de8bd74/ ======================================================================== 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, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html 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/python/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 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-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From hg at nospam.com Fri Nov 24 16:32:11 2006 From: hg at nospam.com (hg) Date: Fri, 24 Nov 2006 15:32:11 -0600 Subject: Active State and Komodo... In-Reply-To: <1164401579.895042.47000@l39g2000cwd.googlegroups.com> References: <1164401579.895042.47000@l39g2000cwd.googlegroups.com> Message-ID: John Machin wrote: > Steve Thompson wrote: >> Hello all, >> >> I was wondering the differnced there were betwee Active State's python and >> the open source version of python. Would I have to unistall my opend souce >> python? Additonally, how does Active State's Komodo IDE vs. the eric3 IDE >> unler SuSE Linux v. 10.i? >> >> Addionally, is the eric IDE (version 3) an acceptible IDE or are there >> more easy and more productive IDE's for perl? >> >> I'm urining Gnome v. 12.2.2 and Eric v 3.8.1 > > I'm not sure which to recommend: a spelling checker or a catheter :-) > You _are_ bad ! From mike.klaas at gmail.com Wed Nov 29 00:56:40 2006 From: mike.klaas at gmail.com (Klaas) Date: 28 Nov 2006 21:56:40 -0800 Subject: How to increase the speed of this program? In-Reply-To: <1164750155.735437.37680@n67g2000cwd.googlegroups.com> References: <1164699156.682944.97410@j44g2000cwa.googlegroups.com> <1164706548.778583.267730@n67g2000cwd.googlegroups.com> <1164714786.086910.288450@45g2000cws.googlegroups.com> <1164739788.335821.239100@n67g2000cwd.googlegroups.com> <1164741116.583861.278220@l12g2000cwl.googlegroups.com> <1164750155.735437.37680@n67g2000cwd.googlegroups.com> Message-ID: <1164779800.685756.66420@l39g2000cwd.googlegroups.com> Klaas wrote: > Klaas wrote: > > > In fact, you can make it about 4x faster by balancing: > > > > [klaas at worbo ~]$ python -m timeit -s "from array import array" > > "array('c','\0'*200)*500" > > 10000 loops, best of 3: 32.4 usec per loop > > This is an unclean minimally-tested patch which achieves reasonable > performance (about 10x faster than unpatched python): Never mind, that patch is bogus. A updated patch is here: http://sourceforge.net/tracker/index.php?func=detail&aid=1605020&group_id=5470&atid=305470 -Mike From walterbyrd at iname.com Thu Nov 16 12:46:05 2006 From: walterbyrd at iname.com (walterbyrd) Date: 16 Nov 2006 09:46:05 -0800 Subject: Python v PHP: fair comparison? In-Reply-To: <2006111607574875249-jameshcunningham@gmailcom> References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> <1163605059.270769.293290@m73g2000cwd.googlegroups.com> <455baf21$0$28561$426a74cc@news.free.fr> <1163642366.698784.130390@i42g2000cwa.googlegroups.com> <2006111523045616807-jameshcunningham@gmailcom> <2006111607574875249-jameshcunningham@gmailcom> Message-ID: <1163699165.847310.285630@e3g2000cwe.googlegroups.com> James Cunningham wrote: > Nope. It disproves your assertion that "certainly all of the lower > priced hosters" use Apache 1.3. Okay, where can I get Python and Apache 2.X for $10 a year? From carsten at uniqsys.com Fri Nov 17 11:03:22 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 17 Nov 2006 11:03:22 -0500 Subject: String Replace only if whole word? In-Reply-To: <005401c70a5f$156e9cd0$0d7d12ac@kearfott.com> References: <005401c70a5f$156e9cd0$0d7d12ac@kearfott.com> Message-ID: <1163779402.3358.9.camel@dot.uniqsys.com> On Fri, 2006-11-17 at 10:43 -0500, Michael Yanowitz wrote: > >Your pattern would be "[^A-Za-z0-9_]word[^A-Za-z0-9_]" > > > >-- > >Juho Schultz > > > Thanks. > This works great except for one thing: > > The character after the replacement is deleted, so that if I have > send_data (LAPTOP, test_string) > it would replace it with: > send_data (10.1.3.4 test_string) > (ignoring that the 10.1.3.4 is not quoted). The comma is missing. If you actually wanted to use string replacement, you'd need a pattern with look-behind and look-ahead assertions along the lines of "(? The (excellent) ElementLibrary ads namespaces to each element when writing the tree back to a file. Say I do: tree = ET.parse('playlist.xml') tree.write(outFile) with the following XML: ============= Kick off! ============= Writing the tree out after adding/removing elements results in: ============= Kick off! ============= Unfortunately the client that needs to consume this XML can't handle the 'ns0:' part of each tag. Is there a way to output XML similar to the input? From mail at microcorp.co.za Mon Nov 20 00:20:13 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 20 Nov 2006 07:20:13 +0200 Subject: [ANN] rpncalc-2.5 RPN Calculator for Python References: Message-ID: <01bf01c70c6b$bec405a0$03000080@hendrik> "Raymond L. Buvel" wrote: > The rpncalc package adds an interactive Reverse Polish Notation (RPN) Can anyone remember who the Pole was and how his name is spelled? (no fair googling) - Hendrik From jm.suresh at gmail.com Tue Nov 28 07:02:23 2006 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 28 Nov 2006 04:02:23 -0800 Subject: Modifying every alternate element of a sequence In-Reply-To: <1164713164.043283.161370@l39g2000cwd.googlegroups.com> References: <1164710289.544394.101170@h54g2000cwb.googlegroups.com> <1164713164.043283.161370@l39g2000cwd.googlegroups.com> Message-ID: <1164715343.290824.239550@14g2000cws.googlegroups.com> Wow, I was in fact searching for this syntax in the python tutorial. It is missing there. Is there a reference page which documents all possible list comprehensions. -- Suresh Leo Kislov wrote: > jm.suresh at no.spam.gmail.com wrote: > > I have a list of numbers and I want to build another list with every > > second element multiplied by -1. > > > > input = [1,2,3,4,5,6] > > wanted = [1,-2,3,-4,5,-6] > > > > I can implement it like this: > > > > input = range(3,12) > > wanted = [] > > for (i,v) in enumerate(input): > > if i%2 == 0: > > wanted.append(v) > > else: > > wanted.append(-v) > > > > But is there any other better way to do this. > > Use slices: > > input[1::2] = [-item for item in input[1::2]] > > If you don't want to do it in-place, just make a copy: > > wanted = input[:] > wanted[1::2] = [-item for item in wanted[1::2]] > > -- Leo From bignose+hates-spam at benfinney.id.au Thu Nov 23 20:04:31 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 24 Nov 2006 12:04:31 +1100 Subject: The Python Papers Edition One References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <7xodqyn5kd.fsf@ruckus.brouhaha.com> <1164323350.988946.209350@l12g2000cwl.googlegroups.com> Message-ID: <87zmahu02o.fsf@benfinney.id.au> "tleeuwenburg at gmail.com" writes: > Yes, it's true that you can't resell copies of The Python Papers for > personal profits, but you may derive from it, reproduce and > propagate it. You're quite right to point it out. Then please revise the false statement that the publication is "free as in beer and freedom", or make it true by releasing the documents under a license that does grant conventional free-software freedoms. -- \ "They can not take away our self respect if we do not give it | `\ to them." -- Mahatma Gandhi | _o__) | Ben Finney From steven.bethard at gmail.com Wed Nov 22 17:45:21 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 22 Nov 2006 15:45:21 -0700 Subject: Global object In-Reply-To: <1164233669.952808.148210@j44g2000cwa.googlegroups.com> References: <1164233669.952808.148210@j44g2000cwa.googlegroups.com> Message-ID: Ghido wrote: > Hi all, i need to save in an object some variable for use in other > parts of my software. it's possibile without create an istance of this > class in every file? if yes how? Create a module, say, ``config``. Then to save your object, you use something like:: import config config.value = value_to_save Now if you want to access it from other parts of your program, simply write:: import config do_something_with(config.value) STeVe From jorge.vargas at gmail.com Sat Nov 4 08:55:21 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Sat, 4 Nov 2006 13:55:21 +0000 Subject: Forum written in Python? In-Reply-To: References: Message-ID: <32822fe60611040555s4722c4d2nb452a23976e90e6b@mail.gmail.com> On 11/2/06, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > Are there any forum or bulletin board systems written entirely in Python? > I got sick of PhpBB, mostly because I can't tweak and fiddle with the > code, since I really don't like PHP and don't know it that well. > > I thought of writting my own simple forum software, but if there are > existing projects out there, I wouldn't mind contributing. So far I found > out about Pocoo, but it seems to immature right now, I was looking for > something comparable to PhpBB or IPB? > why not contribute to Pocoo? > > -- > _______ Karlo Lozovina - Mosor > | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 > | || _ | _ | Parce mihi domine quia Dalmata sum. > |__|_|__||_____|_____| > -- > http://mail.python.org/mailman/listinfo/python-list > From theller at ctypes.org Thu Nov 30 14:21:33 2006 From: theller at ctypes.org (Thomas Heller) Date: Thu, 30 Nov 2006 20:21:33 +0100 Subject: DDE (eSignal) In-Reply-To: <1164912970.711046.214060@80g2000cwy.googlegroups.com> References: <1164912970.711046.214060@80g2000cwy.googlegroups.com> Message-ID: BBands schrieb: > I have a Python ap that needs current stock prices, which I want to get > from eSignal's DDE server. Following the win32all example: > > import win32ui > import dde > server = dde.CreateServer() > server.Create("eSignalDDE") > conversation = dde.CreateConversation(server) > conversation.ConnectTo("WINROS", "Last") > last = conversation.Request("$spx") > print last > > Which almost works. The return in PythonWin is the correct price as a > string with some extra chartacters appended. > > '1402.670000000000\x00\x12\x00*\x00\x00\x004\xfb\x12\x00\xfd\x1a\xd9w4\xc1\x00' > > Any thoughts on this? > > TIA, > > jab > Looks like a bug, either in the dde module or the dde server. But it's easy to find a workaround: >>> '1402.670000000000\x00\x12\x00*\x00\x00\x004\xfb\x12\x00\xfd\x1a\xd9w4\xc1\x00'.split("\0")[0] '1402.670000000000' >>> Thomas From __peter__ at web.de Thu Nov 23 05:55:46 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Nov 2006 11:55:46 +0100 Subject: How do I find possible matches using regular expression? References: <1164272307.978986.158810@l39g2000cwd.googlegroups.com> Message-ID: Andy wrote: > I'm trying to do some predicting work over user input, here's my > question: > > for pattern r'match me', the string 'no' will definitely fail to match, > but 'ma' still has a chance if user keep on inputting characters after > 'ma', so how do I mark 'ma' as a possible match string? The following may or may not work in the real world: import re def parts(regex, flags=0): candidates = [] for stop in reversed(range(1, len(regex)+1)): partial = regex[:stop] try: r = re.compile(partial + "$", flags) except re.error: pass else: candidates.append(r) candidates.reverse() return candidates if __name__ == "__main__": candidates = parts(r"[a-z]+\s*=\s*\d+", re.IGNORECASE) def check(*args): s = var.get() for c in candidates: m = c.match(s) if m: entry.configure(foreground="#008000") break else: entry.configure(foreground="red") import Tkinter as tk root = tk.Tk() var = tk.StringVar() var.trace_variable("w", check) entry = tk.Entry(textvariable=var) entry.pack() root.mainloop() The example lets you write an assignment of a numerical value, e. g meaning = 42 and colours the text in green or red for legal/illegal entries. Peter From sjmachin at lexicon.net Thu Nov 16 06:23:50 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 Nov 2006 03:23:50 -0800 Subject: split CSV fields In-Reply-To: <1163675506.590469.251910@h48g2000cwc.googlegroups.com> References: <1163674830.440318.246920@f16g2000cwb.googlegroups.com> <1163675506.590469.251910@h48g2000cwc.googlegroups.com> Message-ID: <1163676230.105303.39550@m73g2000cwd.googlegroups.com> John Machin wrote: > John Machin wrote: > > Fredrik Lundh wrote: > > > robert wrote: > > > > > > > What is a most simple expression for splitting a CSV line > > > > with "-protected fields? > > > > > > > > s='"123","a,b,\"c\"",5.640' > > > > > > import csv > > > > > > the preferred way is to read the file using that module. if you insist > > > on processing a single line, you can do > > > > > > cols = list(csv.reader([string])) > > > > > > > > > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > > (Intel)] on win32 > > | >>> import csv > > | >>> s='"123","a,b,\"c\"",5.640' > > | >>> cols = list(csv.reader([s])) > > | >>> cols > > [['123', 'a,b,c""', '5.640']] > > # maybe we need a bit more: > > | >>> cols = list(csv.reader([s]))[0] > > | >>> cols > > ['123', 'a,b,c""', '5.640'] > > > > I'd guess that the OP is expecting 'a,b,"c"' for the second field. > > > > Twiddling with the knobs doesn't appear to help: > > > > | >>> list(csv.reader([s], escapechar='\\'))[0] > > ['123', 'a,b,c""', '5.640'] > > | >>> list(csv.reader([s], escapechar='\\', doublequote=False))[0] > > ['123', 'a,b,c""', '5.640'] > > > > Looks like a bug to me; AFAICT from the docs, the last attempt should > > have worked. > > Given Peter Otten's post, looks like > (1) there's a bug in the "fmtparam" mechanism -- it's ignoring the > escapechar in my first twiddle, which should give the same result as > Peter's. > (2) > | >>> csv.excel.doublequote > True > According to my reading of the docs: > """ > doublequote > Controls how instances of quotechar appearing inside a field should be > themselves be quoted. When True, the character is doubled. When False, > the escapechar is used as a prefix to the quotechar. It defaults to > True. > """ > Peter's example should not have worked. Doh. The OP's string was a raw string. I need some sleep. Scrap bug #1! | >>> s=r'"123","a,b,\"c\"",5.640' | >>> list(csv.reader([s]))[0] ['123', 'a,b,\\c\\""', '5.640'] # What's that??? | >>> list(csv.reader([s], escapechar='\\'))[0] ['123', 'a,b,"c"', '5.640'] | >>> list(csv.reader([s], escapechar='\\', doublequote=False))[0] ['123', 'a,b,"c"', '5.640'] And there's still the problem with doublequote .... Goodnight ... From fredrik at pythonware.com Sun Nov 19 12:00:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Nov 2006 18:00:07 +0100 Subject: Reloading after from adder import * ???? In-Reply-To: <1163953912.965436.8880@m73g2000cwd.googlegroups.com> References: <1163901449.418534.251060@b28g2000cwb.googlegroups.com> <1163914443.703646.64080@k70g2000cwa.googlegroups.com> <1163953912.965436.8880@m73g2000cwd.googlegroups.com> Message-ID: Seymour wrote: > I just made some typos and was wondering if there was an easier > way to clear the Python namespace at the interactive prompt rather than > shutting Komodo down and restarting (really brute force). most IDE's have a "reset interactive mode" command (it's ctrl-F6 in IDLE, for example). another approach is to put the code in a script file, and run that file. scripts always run in a clean namespace. yet another approach is to stop using wildcard import ("from import *"). if you refer to the things in Adder via the Adder namespace, you can just do reload(Adder) to fetch the new version. ("from import *" is generally considered a "only use if you know what you're doing" construct in Python, so if it causes trouble for you, you shouldn't have used it in the first place, per definition ;-) From email at christoph-haas.de Fri Nov 24 06:42:43 2006 From: email at christoph-haas.de (Christoph Haas) Date: Fri, 24 Nov 2006 12:42:43 +0100 Subject: Email headers and non-ASCII characters In-Reply-To: <4565bed2$0$13950$edfadb0f@dread15.news.tele.dk> References: <4565bed2$0$13950$edfadb0f@dread15.news.tele.dk> Message-ID: <200611241242.43414.email@christoph-haas.de> On Thursday 23 November 2006 16:31, Max M wrote: > Christoph Haas skrev: > > Hello, everyone... > > > > I'm trying to send an email to people with non-ASCII characters in > > their names. A recpient's address may look like: > > > > "J?rg N?rgens" > > > > My example code: > > > > ================================= > > def sendmail(sender, recipient, body, subject): > > message = MIMEText(body) > > message['Subject'] = Header(subject, 'iso-8859-1') > > message['From'] = Header(sender, 'iso-8859-1') > > message['To'] = Header(recipient, 'iso-8859-1') > > > > s = smtplib.SMTP() > > s.connect() > > s.sendmail(sender, recipient, message.as_string()) > > s.close() > > ================================= > > > > However the Header() method encodes the whole expression in > > ISO-8859-1: > > > > =?iso-8859-1?q?=22J=C3=B6rg_N=C3=B8rgens=22_=3Cjoerg=40nowhere=3E?= > > > > However I had expected something like: > > > > "=?utf-8?q?J=C3=B6rg?= =?utf-8?q?_N=C3=B8rgens?=" > > > > Of course my mail transfer agent is not happy with the first string > > Why offcourse? Because my MTA doesn't care about MIME. It just transports the email. And it expects an email address in <...> but doesn't decode =?iso...? strings. > But it seems that you are passing the Header object a > utf-8 encoded string, not a latin-1 encoded. > You are telling the header the encoding. Not asking it to encode. Uhm, okay. Let's see: u'"J?rg N?rgens" '.encode('latin-1') => '"J\xc3\xb6rg N\xc3\xb8rgens" ' So far so good. Now run Header() on it: => '=?utf-8?b?IkrDtnJnIE7DuHJnZW5zIiA8am9lcmdAbm93aGVyZT4=?=' Still nothing like <...> in it and my MTA is unhappy again. What am I missing? Doesn't anyone know how mail clients handle that encoding? Desperately, Christoph From stefan.behnel-n05pAM at web.de Tue Nov 21 12:34:45 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 21 Nov 2006 18:34:45 +0100 Subject: Spyce system requirements? In-Reply-To: <1164127246.887153.98820@m7g2000cwm.googlegroups.com> References: <1164127246.887153.98820@m7g2000cwm.googlegroups.com> Message-ID: <456338B5.9000705@web.de> walterbyrd wrote: > Does anybody know? What versionof Apache is required? If used with > mod_python, what version of mod_python? Why version of Python is > required? I don't think it has any requirements in that regard. Just try it. You can even use it to generate static web pages. Stefan From apardon at forel.vub.ac.be Tue Nov 28 06:36:55 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Nov 2006 11:36:55 GMT Subject: Modifying every alternate element of a sequence References: <1164710289.544394.101170@h54g2000cwb.googlegroups.com> Message-ID: On 2006-11-28, jm.suresh at no.spam.gmail.com wrote: > I have a list of numbers and I want to build another list with every > second element multiplied by -1. > > input = [1,2,3,4,5,6] > wanted = [1,-2,3,-4,5,-6] > > I can implement it like this: > > input = range(3,12) > wanted = [] > for (i,v) in enumerate(input): > if i%2 == 0: > wanted.append(v) > else: > wanted.append(-v) > > But is there any other better way to do this. Wether this is better, I'll leave that for others to decide. But this is a possibility: wanted = [ (1 - 2*(i%2)) * item for i, item in enumerate(input)] -- Antoon Pardon From aisaac at american.edu Sun Nov 12 06:49:12 2006 From: aisaac at american.edu (Alan G Isaac) Date: Sun, 12 Nov 2006 11:49:12 GMT Subject: Fredrik Lundh [was "Re: explicit self revisited"] References: <1163288444.893136.42030@h54g2000cwb.googlegroups.com> <1163315672.921664.306460@e3g2000cwe.googlegroups.com> Message-ID: On Sun, 12 Nov 2006 02:14:32 -0500, Doug wrote: > I was going to link to > a definition of FUD to show I really meant to use that term. Oooh. If you had just mentioned your dyslogia, it would have saved us all some time. Thanks! Alan From B.Ogryczak at gmail.com Wed Nov 29 12:27:03 2006 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 29 Nov 2006 09:27:03 -0800 Subject: pickle and infinity In-Reply-To: <1164820161.480995.180500@l12g2000cwl.googlegroups.com> References: <1164820161.480995.180500@l12g2000cwl.googlegroups.com> Message-ID: <1164821223.799371.71730@14g2000cws.googlegroups.com> To make things more interesting -- Solaris version: >>> x = 1e310 >>> x Infinity >>> import pickle >>> pickle.dumps(x) 'FInfinity\n.' >>> pickle.loads(_) Infinity >>> pickle.dumps(x,1) [...] SystemError: frexp() result out of range From fredrik at pythonware.com Tue Nov 14 09:14:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Nov 2006 15:14:50 +0100 Subject: Programmatically finding "significant" data points References: <1163513101.580610.151420@b28g2000cwb.googlegroups.com> Message-ID: "erikcw" wrote: > I have a collection of ordered numerical data in a list. The numbers > when plotted on a line chart make a low-high-low-high-high-low (random) > pattern. I need an algorithm to extract the "significant" high and low > points from this data. > > Here is some sample data: > data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, > 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, > 0.10] silly solution: for i in range(1, len(data)-1): if data[i-1] < data[i] > data[i+1] or data[i-1] > data[i] < data[i+1]: print i (the above doesn't handle the "edges", but that's easy to fix) From tjreedy at udel.edu Tue Nov 14 14:41:18 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 14 Nov 2006 14:41:18 -0500 Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com><455226c0$0$17087$c3e8da3@news.astraweb.com><45530513$0$25102$426a74cc@news.free.fr><45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au><4554AAB4.10002@hobbshouse.org> <4554D416.70408@hobbshouse.org> <4554ECBF.7040603@hobbshouse.org> <4558BEC3.3020003@hobbshouse.org> <4558D443.1030802@hobbshouse.org> <4558DBEF.8010409@hobbshouse.org> <02da01c707c2$8345fb80$03000080@hendrik> <17753.63965.96495.419227@montanaro.dyndns.org> Message-ID: wrote in message news:17753.63965.96495.419227 at montanaro.dyndns.org... > >> I confess I find myself in the position of a Yorkshire Youngster - > I > >> don't believe you! > > Robert> Okay, not often enough or annoyingly enough for me to remember > Robert> having done so. Perhaps seven years ago when I started using > Robert> Python, but not any time recent. > > If your editor knows about Python's block structure (as Emacs's > python-mode > does), when you forget the colon it's immediately obvious because the > next > line doesn't autoindent properly. The same is true of the editor in IDLE. From Leo.Kislov at gmail.com Wed Nov 29 07:33:10 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 29 Nov 2006 04:33:10 -0800 Subject: Problem with imaplib (weird result if mailbox contains a %) In-Reply-To: References: <1164727244.400677.36150@l12g2000cwl.googlegroups.com> Message-ID: <1164803590.454993.141050@j72g2000cwa.googlegroups.com> Antoon Pardon wrote: > On 2006-11-28, Leo Kislov wrote: > > > > Antoon Pardon wrote: > >> This little program gives IMO a strange result. > >> > >> import imaplib > >> > >> user = "cpapen" > >> > >> cyr = imaplib.IMAP4("imap.vub.ac.be") > >> cyr.login("cyrus", "cOn-A1r") > >> rc, lst = cyr.list('""', "user/%s/*" % user) > >> for el in lst: > >> print "%r" % (el,) > >> > >> And the result is: > >> > >> '(\\HasNoChildren) "/" "user/cpapen/Out"' > >> '(\\HasNoChildren) "/" "user/cpapen/Punten"' > >> '(\\HasNoChildren) "/" "user/cpapen/Spam"' > >> '(\\HasNoChildren) "/" "user/cpapen/agoog to be"' > >> '(\\HasNoChildren) "/" "user/cpapen/artistiek &- kunst"' > >> '(\\HasNoChildren) "/" "user/cpapen/copains et copinnes =x="' > >> '(\\HasNoChildren) "/" "user/cpapen/cp &- writing"' > >> '(\\HasNoChildren) "/" "user/cpapen/examen"' > >> '(\\HasNoChildren) "/" "user/cpapen/important info (pass)"' > >> '(\\HasNoChildren) "/" "user/cpapen/lesmateriaal"' > >> '(\\HasNoChildren) "/" "user/cpapen/love &- flesh for fantasy"' > >> '(\\HasNoChildren) "/" "user/cpapen/media"' > >> '(\\HasNoChildren) "/" "user/cpapen/music &- beats"' > >> ('(\\HasNoChildren) "/" {25}', 'user/cpapen/newsletters %') > >> '' > >> '(\\HasNoChildren) "/" "user/cpapen/organisatie &- structuur"' > >> '(\\HasNoChildren) "/" "user/cpapen/sociale wetenschappen"' > >> '(\\HasNoChildren) "/" "user/cpapen/the closest ones to me [x]"' > >> '(\\HasNoChildren) "/" "user/cpapen/vubrations"' > >> '(\\HasNoChildren) "/" "user/cpapen/wm2addressbook"' > >> '(\\HasNoChildren) "/" "user/cpapen/wm2prefs"' > >> '(\\HasNoChildren) "/" "user/cpapen/wm2signature"' > >> > >> > >> What I have a problem with is the 14th and 15th line. > >> All other entries are strings but the 14th is a tuple. > >> and the 15th is an empty string. As far as I can tell > >> every time a "%" is in the mailbox name I get this kind of > >> result. > >> > >> I'm using python 2.3.3 and the imap sytem is Cyrus. > >> > >> Can someone explain what is going one? > >> > >> Is this a bug? > > > > Empty string seems to be a bug. But tuple is by design, read the docs > > and imap rfc. The protocol is convoluted in the first place, and so is > > python interface. > > Are there more docs than at http://www.python.org/doc/. I don't find > those very helpfull in explaining this. > > I also took a look at rfc 2060 and to be honest I don't find anything > there to explain this difference. I only took a closer look at section > 7.2.2. So maybe I should look somewehere else but after reading section > 7.2.2. I don't understand why the list method returned a tuple for this > mailbox instead of the following string: > > '(\\HasNoChildren) "/" "user/cpapen/newsletters %"' This is described in section 4.3. imaplib is too close to the protocol. It should interpret response for each command separately. For example list method could return list of tuples like: ("\\HasNoChildren", "/", "user/cpapen/newsletters %") Without this abstraction level in imaplib you have to build it yourself. > > > >> If it is, is it fixed in later versions? > > > > Why don't you try to pull imaplib.py from later versions? I don't think > > it changed that much so it should be compatible with python 2.3 > > I could take my hands on a 2.4 version and the result was the same. I was talking only about empty string response. Is it still there? Anyway, this issue requires investigation. That could also be a bug in the server. -- Leo From paul at boddie.org.uk Thu Nov 16 05:47:06 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Nov 2006 02:47:06 -0800 Subject: lxml/ElementTree and .tail References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> Message-ID: <1163674026.032623.151600@e3g2000cwe.googlegroups.com> Fredrik Lundh wrote: > > It's not very difficult, really; especially if you, as Stefan said, > think in infoset terms rather "a sequence of little piggies" terms. Are piggies part of the infoset too? Does the Piggie class represent a piggie from the infoset plus a stretch of the road to the market? ;-) Paul From luismgz at gmail.com Thu Nov 16 12:20:32 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 16 Nov 2006 09:20:32 -0800 Subject: Python v PHP: fair comparison? In-Reply-To: References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> <1163681949.338244.323390@k70g2000cwa.googlegroups.com> Message-ID: <1163697632.352189.110920@h54g2000cwb.googlegroups.com> Fredrik Lundh ha escrito: > Luis M. Gonz?lez wrote: > > > But as a web development language, it's olnly when people started to > > look for the "rails killer" and many python alternatives started to > > come up (although Django has been in development for a long time before > > all this hype). > > nah, people have built web stuff on Python for as long as we've had a web. > > I know, but would you consider a python cgi application a good competence against php? From bignose+hates-spam at benfinney.id.au Thu Nov 9 23:09:57 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 10 Nov 2006 15:09:57 +1100 Subject: how is python not the same as java? References: <1163119480.524214.186540@e3g2000cwe.googlegroups.com> Message-ID: <87k624j622.fsf@benfinney.id.au> Steve Holden writes: > Java is horrible, Oython is not. Is that the predecessor to Python, the one that could only be expressed in vowel noises? -- \ "Beware of and eschew pompous prolixity." -- Charles A. | `\ Beardsley | _o__) | Ben Finney From mirandacascade at yahoo.com Mon Nov 20 12:26:38 2006 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 20 Nov 2006 09:26:38 -0800 Subject: ElementSOAP and In-Reply-To: References: <1164007864.239490.20810@k70g2000cwa.googlegroups.com> Message-ID: <1164043598.088253.29790@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > make sure you have the 0.5 release May I confirm the following recommendations/dependencies: 1) if one wants to use ElementSOAP to create a message that includes , it is recommended that one use the 0.5 release of ElementSOAP 2) if one wants to use the 0.5 release of ElementSOAP, one should be using Python 2.5 Thank you. From paul at boddie.org.uk Thu Nov 16 19:37:40 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Nov 2006 16:37:40 -0800 Subject: Secure Python References: <455c1665@quokka.wn.com.au> <455c4d9b@quokka.wn.com.au> <4s38t9Ftln2aU1@mid.uni-berlin.de> <1163689149.613418.40020@b28g2000cwb.googlegroups.com> <455cfea5$1@quokka.wn.com.au> Message-ID: <1163723860.233529.17400@m7g2000cwm.googlegroups.com> timmy wrote: > Paul Boddie wrote: > > Diez B. Roggisch wrote: [Re-adding material...] > >>At least to me - and I presume pretty much everybody except you in this > >>thread - this means that he is interested in executing arbitrary pieces of > >>python code inside the interpreter, which comes from e.g. players who > >>customize their in-game behavior of their avatars. Here is where the issue of sandboxing is indirectly introduced into the discussion. > >>Now how exactly does linux (or any other resource limiting technique on any > >>OS) help here - killing the whole game server surely isn't a desirable > >>solution when one player goes berserk, might it be intentionally or not. > > > And this is where the hot topics collide: people want performant > > multitasking with lots of shared state (the global interpreter lock > > controversy) together with sandboxing so that the individual threads > > can't access most of that shared state (the restricted execution > > controversy). > > i'm not talking about sandboxing, that's a whole different kettle of > fish. i'm talking about resource managment options you can set in for > instance, the linux kernel. Yes, I know. I was merely covering related concepts of relevance introduced earlier in the discussion (see above). In any case, if you only have control over resource limits on execution contexts at the operating system process level, yet your server architecture is entirely based on a single process with many (micro)threads, then you've got to consider the problem of restricting their behaviour/consumption using the facilities available to you, most likely by considering other server architectures. This, I argue, is perfectly reasonable in order to solve both issues being discussed using operating system facilities. > you can limit the cpu and memory a process uses while still allowing it > the same access it would have outside of a sandbox. that way if any > clever monkeys try to dos you they merely consume their alloted quota. Indeed. Paul From fredrik at pythonware.com Wed Nov 15 03:37:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Nov 2006 09:37:48 +0100 Subject: FAQ: How do I calculate what quoted strings and numbers mean? In-Reply-To: <1163579122.362383.203240@k70g2000cwa.googlegroups.com> References: <1163168083.054745.32170@f16g2000cwb.googlegroups.com> <1163579122.362383.203240@k70g2000cwa.googlegroups.com> Message-ID: p.lavarre at ieee.org wrote: > I was happy enough when I saw an improvement like: > >>>> import os >>>> result = eval("os.system('pwd')") > .../Desktop >>>> result = eval("os.system('pwd')", {"whatever": {}}) > Traceback (most recent call last): > File "", line 1, in > File "", line 1, in > NameError: name 'os' is not defined sure, but the os module isn't very far away: >>> result = eval("__import__('os').system('pwd')", {"whatever": {}}) /home/fredrik From skip at pobox.com Tue Nov 14 12:16:13 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 14 Nov 2006 11:16:13 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <4554D416.70408@hobbshouse.org> <4554ECBF.7040603@hobbshouse.org> <4558BEC3.3020003@hobbshouse.org> <4558D443.1030802@hobbshouse.org> <4558DBEF.8010409@hobbshouse.org> <02da01c707c2$8345fb80$03000080@hendrik> Message-ID: <17753.63965.96495.419227@montanaro.dyndns.org> >>> Michael Hobbs wrote: >>>> True enough. Although, I have to ask how many times you define a new >>>> function only to have Python spit a syntax error out at you saying that >>>> you forgot a colon. It happens to me all the time. >> >> I confess I find myself in the position of a Yorkshire Youngster - I >> don't believe you! Robert> Okay, not often enough or annoyingly enough for me to remember Robert> having done so. Perhaps seven years ago when I started using Robert> Python, but not any time recent. If your editor knows about Python's block structure (as Emacs's python-mode does), when you forget the colon it's immediately obvious because the next line doesn't autoindent properly. Skip From bignose+hates-spam at benfinney.id.au Sun Nov 26 19:59:57 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 27 Nov 2006 11:59:57 +1100 Subject: The Python Papers Edition One References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <1164106267.882164.124670@h48g2000cwc.googlegroups.com> <1164156093.359433.315790@e3g2000cwe.googlegroups.com> <1164471238.033790.243890@14g2000cws.googlegroups.com> <1164586594.649105.282020@h54g2000cwb.googlegroups.com> Message-ID: <87wt5hsnzm.fsf@benfinney.id.au> "Noah Slater" writes: > I do not think this thread is an embarrassment to the community. I > think it speaks volumes about people's commitment to free software. > > While we can applaud such contributions it is no excuse to waiver on > one's ethics and principles. Yes, this was also my motivation for discussing it here. > Regardless of content, or even format, if the Python Papers are not > free as per the FSF's definition they are encumbered. > > I am hoping that the author/publishers will reconsider the choice of > licencing. I also hope that a free license can be chosen. In the meantime though, I'm very happy that (as announced in a new thread) the existing license terms are no longer being falsely described as free. -- \ "If you ever drop your keys into a river of molten lava, let | `\ 'em go, because, man, they're gone." -- Jack Handey | _o__) | Ben Finney From bj_666 at gmx.net Sat Nov 4 08:50:51 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 04 Nov 2006 14:50:51 +0100 Subject: WSDL? References: <454ba334$0$12110$88260bb3@free.teranews.com> Message-ID: In , Jorge Vargas wrote: > and please please don't go to corba we need to kill that. Have you real reasons or is this a religious thing? As I see it Corba is much better supported by Python libs than SOAP is. Ciao, Marc 'BlackJack' Rintsch From gabor at nekomancer.net Sat Nov 18 04:16:11 2006 From: gabor at nekomancer.net (gabor) Date: Sat, 18 Nov 2006 10:16:11 +0100 Subject: What do I look for in a shared Python host? In-Reply-To: References: <1163815003.733525.6380@b28g2000cwb.googlegroups.com> Message-ID: Gregor Horvath wrote: > walterbyrd schrieb: >> What other "gotchas" would I look for? >> > > Maybe this is helpfull for you: > > http://docs.turbogears.org/1.0/Hosting > and this: http://code.djangoproject.com/wiki/DjangoFriendlyWebHosts gabor From aj108778 at gmail.com Sun Nov 12 02:18:48 2006 From: aj108778 at gmail.com (Doug) Date: 11 Nov 2006 23:18:48 -0800 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> Message-ID: <1163315927.963179.114030@m73g2000cwd.googlegroups.com> Michael Hobbs wrote: > Can anyone find a flaw with this change in syntax? > > Instead of dividing a compound statement with a colon, why not divide it > on a newline? For example, the colon could be dropped from this statement: > if self.hungry: > self.eat() > to > if self.hungry > self.eat() > > Python is already sensitive to whitespace and the newline anyway, so why > not put it to good use? For example, Python rejects this statement > because of the newline present: > if self.hungry or > self.depressed: > self.eat() > You need to use the backslash to continue the expression on the next line: > if self.hungry or \ > self.depressed: > self.eat() > The colon that divides the statement therefore seems redundant. The > colon could continue to be used for single-line statements: > if self.hungry: self.eat() > > I think the colon could be omitted from every type of compound > statement: 'if', 'for', 'def', 'class', whatever. Am I missing anything? > > Thanks, > - Mike It is a very good idea as the colon is technically redundant (not necessary for parsing, aside from one liners) and actually hurts readability (and writeability). The "evidence" people cite for the advantage of using a colon is research done by users of the ABC language, python's predecessor. They forget that A) that was like 20 years ago, B) the language was designed for children, and C) the keywords in ABC are IN ALL CAPS LIKE THIS (hurting readability and writeability) and thus adding a colon obviously helps restore some readability for users in that case but not in python's. However, python is far too old to accept any fundamental changes to syntax at this point. From paul at boddie.org.uk Thu Nov 16 08:19:20 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Nov 2006 05:19:20 -0800 Subject: Python v PHP: fair comparison? References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> <1163681949.338244.323390@k70g2000cwa.googlegroups.com> Message-ID: <1163683160.312575.250620@b28g2000cwb.googlegroups.com> Luis M. Gonz?lez wrote: > > OK. But since when has python been considered a viable alternative for > web development? Since the Bobo era (ca. 1997), but quite possibly before. Sure, you had to build your own mega-framework back then, but that's what a lot of people were doing anyway. > As a generalp purpose language, it's older. > But as a web development language, it's olnly when people started to > look for the "rails killer" and many python alternatives started to > come up (although Django has been in development for a long time before > all this hype). I remember maintaining a long list of Web frameworks a few *years* ago. It's true that most of them didn't resemble the slick marketed package that you see with something like TurboGears, but you might be surprised how much you got with Webware back in 2001: http://www.webwareforpython.org/Docs/RelNotes-0.5.html > I remember well, just a few months ago, there were many alternatives > (remember "subway"?). Some people would like you to believe that they pioneered the mega-framework, amongst other things. Freely available documentation undermines such claims if you know where to look (and actually choose to do so). Paul From dannycolligan at gmail.com Tue Nov 21 11:48:53 2006 From: dannycolligan at gmail.com (Danny Colligan) Date: 21 Nov 2006 08:48:53 -0800 Subject: Vim scripts for editing Python? In-Reply-To: <1164086261.774376.125490@j44g2000cwa.googlegroups.com> References: <1164086261.774376.125490@j44g2000cwa.googlegroups.com> Message-ID: <1164127733.241526.126200@m7g2000cwm.googlegroups.com> Rainy wrote: > Hi, did anyone make a good set of scripts for editing Python in Vim? I > know there is one on vim.org but it isn't very advanced. thx.. Here's what google has to say about it: http://www.google.com/search?hl=en&q=site%3Ahttp%3A%2F%2Fwww.vim.org%2Ftips%2F+python&btnG=Google+Search http://www.google.com/search?hl=en&lr=&safe=off&q=site%3Ahttp%3A%2F%2Fwww.vim.org%2Fscripts%2F+python&btnG=Search Danny From grahamjfeeley at optusnet.com.au Sun Nov 19 04:11:35 2006 From: grahamjfeeley at optusnet.com.au (Graham Feeley) Date: Sun, 19 Nov 2006 19:11:35 +1000 Subject: WebScraping References: <454d0fb1$0$11970$afc38c87@news.optusnet.com.au> Message-ID: <45601fca$0$5106$afc38c87@news.optusnet.com.au> Well I would like to publicly thank Bernard Chhun for actually writing this script and "pretting " it up for me. He is truly a talented guy. He used Beautifull Soup and Regex which i am still coming to terms trying to understand them any way Thanks again Bernard. Regards graham "Graham Feeley" wrote in message news:454d0fb1$0$11970$afc38c87 at news.optusnet.com.au... > Can someone steer me to scripts / modules etc on webscraping please??? > Ultimately I would like someone to write a script for me. > However i am still searching for documentation on this subject > Thanks Graham > > > From dlenski at gmail.com Mon Nov 13 17:26:40 2006 From: dlenski at gmail.com (Dan Lenski) Date: 13 Nov 2006 14:26:40 -0800 Subject: Is python for me? In-Reply-To: References: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> <1163441697.231672.163480@k70g2000cwa.googlegroups.com> Message-ID: <1163456800.148818.181940@m7g2000cwm.googlegroups.com> Carsten Haese wrote: > On Mon, 2006-11-13 at 10:14 -0800, Dan Lenski wrote: > > lennart wrote: > > > So i ask myself is python the language I'm looking for? > > > > Yep! Python is very much a jack-of-all-trades language. > > I'll run the risk of being nitpicky, but the full phrase is "Jack of all > trades, master of none," which doesn't do Python justice. Python is a > master of all trades! Indeed! That's why I left out the "master of none" prt :-) For me, Python is "jack of all trades, master of everything I've thrown at it so far." Dan From steve at REMOVE.THIS.cybersource.com.au Thu Nov 23 06:27:55 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 23 Nov 2006 22:27:55 +1100 Subject: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]? References: Message-ID: On Thu, 23 Nov 2006 10:48:32 +0000, Tor Erik Soenvisen wrote: > Hi, > > > (len(['']) is 1) == (len(['']) == 1) => True You shouldn't rely on this behaviour: >>> x = 100000 >>> len('a' * x) == x True >>> len('a' * x) is x False (Your results may vary -- this depends on the implementation.) > Is this the case for all numbers? I've tried running the following: > > for i in range(10000): > for j in range(10000): > if i != j: > assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id > (i)) > > which executes fine. Hence, 0-9999 is okey... This doesn't necessarily hold for all integers -- again, it depends on the implementation, the precise version of Python, and other factors. Don't rely on "is" giving the same results as "==". >>> (1+2+3+4+5)**7 == 15**7 True >>> (1+2+3+4+5)**7 is 15**7 False > But this is a relatively > small range, and sooner or later you probably get two numbers with the same > id... Thoughts anyone? No, you will never get two objects existing at the same time with the same id. You will get two objects that exist at different times with the same id, since ids may be reused when the object is deleted. > PS: For those of you who don't know: keyword is compares object identities Exactly. There is no guarantee that any specific integer object "1" must be the same object as another integer object "1". It may be, but it isn't guaranteed. I think the only object that is guaranteed to hold for is None. None is a singleton, so there is only ever one instance. Hence, you should test for None with "obj is None" rather than ==, because some custom classes may do silly things with __eq__: class Blank(object): """Compares equal to anything false, including None.""" def __eq__(self, other): return not other -- Steven. From dima at trit.invalid Tue Nov 21 05:55:46 2006 From: dima at trit.invalid (Dima Dorfman) Date: Tue, 21 Nov 2006 10:55:46 -0000 Subject: FreeBSD + Python + Oracle References: Message-ID: On 2006-11-21, Vyacheslav Sotnikov wrote: > is anybody has any success in taking this components live together? I > need to access remote Oracle 9i from freebsd 6.2 machine using python > 2.4.4. Thanks in advance for answer. Yes, I've done this before. You'll have to run Python on FreeBSD but using the Linux ABI ("Linuxulator" or "Linux emulation"). It's a bit of a pain to set up, but it works well after that. The basic procedure is: - Load the linux module and install the linux-base and -devtools ports - Install the Linux Oracle client and get it working enough that you can run sqlplus - Compile Python for the Linux ABI (you'll have to install all the appropriate linux libraries if you need extension modules like gzip, readline, etc.) - Compile the Oracle extension modules. I've successfully used DCOracle2 and cx_Oracle in this scenario. That should be it, but it's been a while since I had to do it and I might've missed some steps. All of the above is okay if you want to run FreeBSD because you like FreeBSD; it doesn't help if you want to do it because you need to use some library that's only available for FreeBSD. In that case, you can probably manage some kind of IPC between Linux-Python-on-FreeBSD and FreeBSD-Python-on-FreeBSD. From bdesth.quelquechose at free.quelquepart.fr Wed Nov 15 19:47:59 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 16 Nov 2006 01:47:59 +0100 Subject: Will GPL Java eat into Python marketshare? In-Reply-To: References: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> Message-ID: <455bb047$0$28561$426a74cc@news.free.fr> John Bokma a ?crit : > Harry George wrote: > > >>Short answer: People use Python instead of Java because people (at >>least intelligent people) tend to avoid pain. > > > Intelligent people don't suffer from fanboy sentiments. They just pick a > language that works best for them. > Which is *exactly* what Harry said... From scott.daniels at acm.org Wed Nov 22 09:47:54 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 22 Nov 2006 06:47:54 -0800 Subject: What's going on here? In-Reply-To: References: Message-ID: <456459ca$1@nntp0.pdx.net> Dale Strickland-Clark wrote: > Python 2.4.2 (#1, Oct 13 2006, 17:11:24) >>>> a = object() >>>> a.spam = 1 > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'object' object has no attribute 'spam' >>>> class B(object): pass >>>> a = B() >>>> a.spam = 1 >>>> > > What is subclassing adding to the class here? Why can't I assign to > attributes of an instance of object? object itself doesn't have a __dict__ slot, so that very small objects (such as points) can be built without that overhead. --Scott David Daniels scott.daniels at acm.org From mail at microcorp.co.za Fri Nov 17 03:06:21 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 17 Nov 2006 10:06:21 +0200 Subject: Secure Python References: <455c1665@quokka.wn.com.au><455c4d9b@quokka.wn.com.au> Message-ID: <035501c70a1f$4557e2c0$03000080@hendrik> "Stephan Kuhagen" wrote: > The problem with linux kernel limits are, that they won't work really good > on MacOSX and Windows... OTOH the idea is the right one, but the effect can > be achieved inside of Python. Since Python does byte compile the code and > the interpreter evaluates each byte code token in one evaluation step. The > interpreter could be extended for such usecases to count and limit the > number of evaluation steps allowed for untrusted script or methods in > untrusted script as well as to limit the recursion depth or memory to be > allocated. All those limits are managed by the interpreter for script code > and hence can be limited for untrusted code by the interpreter. This also > does not really make DoS impossible (what about C extensions? - maybe > restricting "import"?). - As I said before in this thread, making a sandbox > really secure is a hard job, and may need some serious changes in the > Python interpreter, but AFAIK from Tcl, it is possible - and would be nice > to have. I seem to recall previous discussion on this group about a thing called the bastion module, and that it was deprecated. Not sure if it has any relevance. - Hendrik From __peter__ at web.de Sun Nov 19 09:25:20 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 19 Nov 2006 15:25:20 +0100 Subject: tempfile.NamedTemporaryFile wont work References: <456049ca$0$4692$426a74cc@news.free.fr> Message-ID: Steven D'Aprano wrote: > On Sun, 19 Nov 2006 13:11:13 +0100, Imbaud Pierre wrote: > >> On suse 9.3, tempfile.NamedTemporaryFile() doesnt work as expected. > [snip] > >> Symptom: the file does not always exist, after the call to >> NamedTemporaryFile(). Or at least its not seen by the strings command, >> or by os.path.exists. >> >> I guess the bug is pretty much os dependent, or even filesystem >> dependent (Im on reiserfs). Maybe the os is buggy, maybe, somehow, the >> python interface. Or did I miss something? >> Shame, I didnt even try to check for a python bug tracker. > > I can verify this problem occurs on Fedora Core 5 too: > > import os > import sys > import tempfile > import subprocess > def test(n): > chunk = ': +++ abcd +++' > for i in xrange(n): > tf = tempfile.NamedTemporaryFile() > tfName = tf.name > tf.seek(0) > tf.write(str(i) + chunk) > tf.flush() > if not os.path.exists(tfName): > print 'pre-check: %s not there' % tfName > subprocess.Popen(['strings', tfName]) > if not os.path.exists(tfName): > print 'post-check: %s not there' % tfName > > > And here is a typical run, with the boring bits removed for ease of > reading: > >>>> test(30) > 0: +++ abcd +++ > 1: +++ abcd +++ > [ more of the same ] > 14: +++ abcd +++ > strings: '/tmp/tmpOALbx9': No such file > 16: +++ abcd +++ > 17: +++ abcd +++ > 18: +++ abcd +++ > [ more of the same ] > 27: +++ abcd +++ > strings: /tmp/tmpdc52Nz: No such file or directory > 29: +++ abcd +++ > > > Curiouser and curiouser... not only does os.path.exist always report the > temp file as existing (at least in my tests), even when strings can't find > it, but strings returns different error messages. > > Is it possible this is a bug in strings? What /you/ are seeing is not a bug, I think. Popen() is asynchronous, therefore you may enter the second iteration -- which implicitly closes the temporary file -- before strings actually tries to access it. Use call() and everything should be fine. Peter From dickinsm at gmail.com Wed Nov 29 19:31:30 2006 From: dickinsm at gmail.com (dickinsm at gmail.com) Date: 29 Nov 2006 16:31:30 -0800 Subject: Remarkable results with psyco and sieve of Eratosthenes In-Reply-To: <1164844778.623531.275300@h54g2000cwb.googlegroups.com> References: <1164837289.295731.178070@h54g2000cwb.googlegroups.com> <1164843185.361082.146740@16g2000cwy.googlegroups.com> <1164844778.623531.275300@h54g2000cwb.googlegroups.com> Message-ID: <1164846690.746084.174820@80g2000cwy.googlegroups.com> On Nov 29, 6:59 pm, "Steve Bergman" wrote: > dicki... at gmail.com wrote: > > > BTW, can this code be made any more efficient? > > > I'm not sure, but the following code takes around 6 seconds on my > > 1.2Ghz iBook. How does it run on your machine? > > Hmm. Come to think of it, my algorithm isn't the sieve. Right. I guess the point of the sieve is that you don't have to spend any time finding that a given odd integer is not divisible by a given prime; all the multiplies are done up front, so you save all the operations corresponding to the case when x % y != 0 in your code. Or something. > Anyway, this is indeed fast as long as you have enough memory to handle > it for the range supplied. The sieve can be segmented, so that the intermediate space requirement for computing the primes up to n is O(sqrt(n)). (Of course you'll still need O(n/log n) space to store the eventual list of primes.) Then there are all sorts of bells and whistles (not to mention wheels) that you can add to improve the running time, most of which would considerably complicate the code. The book by Crandall and Pomerance (Primes: A Computational Perspective) goes into plenty of detail on all of this. Mark Dickinson From roy at panix.com Tue Nov 14 09:55:11 2006 From: roy at panix.com (Roy Smith) Date: Tue, 14 Nov 2006 09:55:11 -0500 Subject: Programmatically finding "significant" data points References: <1163513101.580610.151420@b28g2000cwb.googlegroups.com> Message-ID: "erikcw" wrote: > I have a collection of ordered numerical data in a list. The numbers > when plotted on a line chart make a low-high-low-high-high-low (random) > pattern. I need an algorithm to extract the "significant" high and low > points from this data. I think you want a control chart. A good place to start might be http://en.wikipedia.org/wiki/Control_chart. Even if you don't actually graph the data, understanding the math behind control charts might help you with your analysis. Wow. I think this is the first time I'm actually used something I learned by sitting though those stupid Six Sigma training classes :-) From onurb at xiludom.gro Tue Nov 14 05:12:01 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 14 Nov 2006 11:12:01 +0100 Subject: to setattr or def setProp() In-Reply-To: <1163485203.560900.286430@b28g2000cwb.googlegroups.com> References: <1163485203.560900.286430@b28g2000cwb.googlegroups.com> Message-ID: <45599673$0$11686$426a74cc@news.free.fr> jm.suresh at no.spam.gmail.com wrote: > I have a class for rectangle and it has two points in its __slots__ . > However, we can derive a number of properties like width, height, > centerPoint etc from these two points. Now, I want to be able to set > and get these properties directly from the instances. I can either def > __setattr__ , __getattr__ But this won't help with introspection... > or I can define function for each property > like setWidth(), setHeight() . Which one would be faster? You mean faster performances or faster to implement ? > I would > prefer doing through __setattr__, __getattr__ because it makes the code > more readable. You mean the client code ? > However, speed is a concern I would have to do these operations in few > thousand iterations for about 50-100 rectangles. > The canonical solution is to use either properties or custom descriptors[1]. Custom descriptors should be a bit faster than properties (since you save a couple function calls), but I have not done any benchmark... It should also be a bit faster than __getattr__, which is only used as a fallback when all other lookup rules have failed (here again, don't take me on words and do some benchmarking). As a last point, descriptors show up as class and instance attributes, which helps with introspection. class Height(object): def __get__(self, instance, cls): if instance is None: return self return instance.bottomright.y - instance.topleft.y def __set__(self, instance, value): instance.bottomright.y = instance.topleft.y + value class Width(object): def __get__(self, instance, cls): if instance is None: return self return instance.bottomright.x - instance.topleft.x def __set__(self, instance, value): instance.bottomright.x = instance.topleft.x + value class Rectangle(object): def __init__(self): self.topleft = Point(10, 10) self.bottomright = Point(20, 30) height = Height() width = Width() r = Rectangle() r.with = 40 (not tested) [1] : * http://docs.python.org/ref/descriptors.html * http://users.rcn.com/python/download/Descriptor.htm My 2 cents... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From peter.maas at utilog.de Mon Nov 13 17:03:55 2006 From: peter.maas at utilog.de (Peter Maas) Date: Mon, 13 Nov 2006 23:03:55 +0100 Subject: explicit self revisited In-Reply-To: References: Message-ID: Steven D'Aprano schrieb: > Implicit self will never be used for Python, because it is redundant so > long as there is a need for explicit self, and there is a need for > explicit self because there are a number of basic, dare I say > *fundamental* programming techniques that require an explicit self. > > For example, delegation. > > class MyClass(Parent): > def method(self, arg): > Parent.method(self, arg) > # what are you going to write? Parent.method(,arg) maybe? The idea is: let self (or self.) be represented by the dot alone, therefore: Parent.method(., arg) # :) > Here's another fundamental technique that implicit self breaks. > > class MyList(list): > def __iadd__(self, other): > # in-place addition > other = transform(other) # do something to the argument > super(MyList, self).__iadd__(other) # call the superclass > # could be written .__class__.__iadd__(other) > # BUT be aware the semantics are NOT the same! > return self # and return the suitably modified instance return . > You can't explicitly return the instance unless you have an explicit name > for it. (And if you are thinking of creating more magic syntax that > implicitly returns self, just don't bother.) No magic. Just a dot. But perhaps a dot is too tiny. We could take JUST_ME or ME_AND_BOBBY_MCGEE instead, of course as a reserved keyword followed by a dot ;) Thanks for your hints, Steven. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From gabrielg_laburando at yahoo.com.ar Mon Nov 13 00:15:51 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Mon, 13 Nov 2006 02:15:51 -0300 Subject: how do i map this? In-Reply-To: <1163393708.532194.250580@k70g2000cwa.googlegroups.com> References: <1163387481.135930.167580@m7g2000cwm.googlegroups.com> <1163393708.532194.250580@k70g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061113021016.01d6d570@yahoo.com.ar> At Monday 13/11/2006 01:55, John Machin wrote: >Ben Finney wrote: > > "ronrsr" writes: > > > > > #row is a dictionary with keys: zid, keywords, citation, quotation > > > def print_row(row): > > > print """ > > > [...] > > > """ > > > > You're printing a string, and never using that 'row' parameter. > >If that is so, why is he getting that message "TypeError: format >requires a mapping"? Apparently the posted code doesn't match the actual code. If that print_row() matched the stack trace, should say % row at the end. Perhaps there is another function print_row? Or you cut something from the end? -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From daigno at gmail.com Thu Nov 16 16:46:05 2006 From: daigno at gmail.com (=?ISO-8859-1?Q?=C9ric_Daigneault?=) Date: Thu, 16 Nov 2006 16:46:05 -0500 Subject: Question about unreasonable slowness Message-ID: <455CDC1D.8010800@gmail.com> [ Warning: I'm new to Python. Don't know it at all really yet, but had to examine some 3rd party code because of performance problems with it. ] Here's a code snippet: i = 0 while (i < 20): i = i + 1 (shellIn, shellOut) = os.popen4("/bin/sh -c ':'") # for testing, the spawned shell does nothing print 'next' # for line in shellOut: # print line On my system (AIX 5.1 if it matters, with Python 2.4.3), this simple loop spawning 20 subshells takes .75 sec. Ok, that's reasonable. Now, if I uncomment the two commented lines, which loop over the empty shellOut array, the progam now takes 11 secs. That slowdown seems very hard to believe. Why should it slow down so much? John. --- Tried it on my comp (battered up winXP laptop on it's last breath) with the following change... (shellIn, shellOut) = os.popen4("cmd ") and the performance with or without the inserted for loop is roughly equivalent albeit a /bit/ slower with the for loop is but I would need timers really make it stand out (under 1 second difference). All in all, rough estimation is that both take more or less 4 seconds to complete which is what I would expect knowing my system... Anyways, is what I got... Hope it helps somehow ?ric :D. From larry.bates at websafe.com Tue Nov 28 12:34:19 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 28 Nov 2006 11:34:19 -0600 Subject: SPE (Stani's Python Editor) web site? In-Reply-To: References: Message-ID: <456C731B.50803@websafe.com> John DeRosa wrote: > SPE's site (http://pythonide.stani.be/) has been inaccessible to me > for at least a day. Can anyone else get to it? > > I looked on Google and didn't see any new locations for SPE. Has it > recently moved to somewhere else? I dimly recall a post by Stani > wherein he said he might move the site, but I can't find it... > > John DNS resolves to 205.234.199.58, but homepage never loads and I get a Proxy Error in browser. FYI, Larry From pierre at saiph.com Sun Nov 19 07:11:13 2006 From: pierre at saiph.com (Imbaud Pierre) Date: Sun, 19 Nov 2006 13:11:13 +0100 Subject: tempfile.NamedTemporaryFile wont work Message-ID: <456049ca$0$4692$426a74cc@news.free.fr> On suse 9.3, tempfile.NamedTemporaryFile() doesnt work as expected. (I found a permanent workaround, so I dont ask for help) I expected to write to a file, and access it thru a shell command. This code, in a loop: tf = tempfile.NamedTemporaryFile() tfName = tf.name #tf.seek(0) # rewind the file tf.write(chunk); tf.flush() print >> sys.stderr, '%s: %s' % (tfName, ['no', 'yes'][os.path.exists(tfName)]) subprocess.Popen(['strings', tfName]) Symptom: the file does not always exist, after the call to NamedTemporaryFile(). Or at least its not seen by the strings command, or by os.path.exists. I guess the bug is pretty much os dependent, or even filesystem dependent (Im on reiserfs). Maybe the os is buggy, maybe, somehow, the python interface. Or did I miss something? Shame, I didnt even try to check for a python bug tracker. From aahz at pythoncraft.com Sat Nov 25 11:19:56 2006 From: aahz at pythoncraft.com (Aahz) Date: 25 Nov 2006 08:19:56 -0800 Subject: Simple threading References: <1164295697.757788.26710@e3g2000cwe.googlegroups.com> <12mgkd6e5cp5l16@corp.supernews.com> Message-ID: In article <12mgkd6e5cp5l16 at corp.supernews.com>, Grant Edwards wrote: > >Re-binding a name is always an atomic operation. Modifying >many mutable objects is atomic. You know this, but just to make clear: rebinding attributes of an object (which are also sometimes called names) is not necessarily an atomic operation. Moreover, only a plain rebinding operation is atomic; augmented assignment is frequently not atomic. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 1993 From timothy at open-networks.net Thu Nov 16 06:37:42 2006 From: timothy at open-networks.net (timmy) Date: Thu, 16 Nov 2006 21:37:42 +1000 Subject: Secure Python In-Reply-To: References: <455c1665@quokka.wn.com.au> Message-ID: <455c4d07@quokka.wn.com.au> Fredrik Lundh wrote: > timmy wrote: > >> congraulations you have discovered loops and their misuse > > > if you don't know what the phrase "denial of service attack" means, you > can always google for it. > > > maybe you should google "linux kernel limit" and you can prevent any user/process maxing out your system From aahz at pythoncraft.com Tue Nov 28 20:09:39 2006 From: aahz at pythoncraft.com (Aahz) Date: 28 Nov 2006 17:09:39 -0800 Subject: why would anyone use python when java is there? References: <1164762232.220759.57160@h54g2000cwb.googlegroups.com> Message-ID: In article <1164762232.220759.57160 at h54g2000cwb.googlegroups.com>, gavino wrote: > >wtf Because programming in Python makes me feel happy and contented, while programming in Java just makes me want to scream in agony. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Usenet is not a democracy. It is a weird cross between an anarchy and a dictatorship. From e0427417 at student.tuwien.ac.at Tue Nov 21 16:58:22 2006 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Tue, 21 Nov 2006 22:58:22 +0100 Subject: Is there a list comprehension for this? In-Reply-To: <1164143944.874745.19470@f16g2000cwb.googlegroups.com> References: <1164143944.874745.19470@f16g2000cwb.googlegroups.com> Message-ID: <45637619$0$12642$3b214f66@tunews.univie.ac.at> liam_herron wrote: > Given: > dw = [ 1, -1.1, +1.2 ] > > Suppose I want to create a list 'w' that is defined as > > w[0] = dw[0], > w[1] = w[0] + dw[1], > w[2] = w[1] + dw[2] > > Is there a list comprehension or map expression to do it in one or 2 > lines. > Is this a function where you just want to know a w[n]? then: def w(n): return sum((1 + i * 0.1) * (i % 2 and 1 or -1) for i in xrange(n)) otherwise: n, w, x = 3, [], 0 for y in ((1 + i * 0.1) * (i % 2 and 1 or -1) for i in xrange(n)): x += y w.append(x) From kibleur.christophe at gmail.com Mon Nov 6 07:47:13 2006 From: kibleur.christophe at gmail.com (Tool69) Date: 6 Nov 2006 04:47:13 -0800 Subject: ANN: PyQt v4.1 Released In-Reply-To: References: <1162749608.733730.321970@k70g2000cwa.googlegroups.com> Message-ID: <1162817233.695765.22780@b28g2000cwb.googlegroups.com> Hi Phil, I followed the docs to build qscintilla2, all is going well with no errors, but when I launched the PyQt Syntax Highlighter Example, nothing is highlighted but the first line of text, whereas the C++ sample works well in the demo. Any hints ? Thanks. From steve at REMOVE.THIS.cybersource.com.au Mon Nov 6 05:43:13 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 06 Nov 2006 21:43:13 +1100 Subject: simple way to un-nest (flatten?) list References: <9Ws3h.47668$r61.11004@text.news.blueyonder.co.uk> Message-ID: On Sun, 05 Nov 2006 21:43:33 +0000, djc wrote: > There is I am sure an easy way to do this, but I seem to be brain dead > tonight. So: > > I have a table such that I can do > > [line for line in table if line[7]=='JDOC'] > and > [line for line in table if line[7]=='Aslib'] > and > [line for line in table if line[7]=='ASLIB'] > etc > > I also have a dictionary > r= {'a':('ASLIB','Aslib'),'j':('JDOC', 'jdoc')} > so I can extract values > r.values() > [('ASLIB', 'Aslib'), ('JDOC', 'jdoc')] > > I would like to do > > [line for line in table if line[7] in ('JDOC','jdoc','Aslib','ASLIB')] What is the purpose of the "if line[7]" bit? > so how should I get from > {'a':('ASLIB','Aslib'),'j':('JDOC','jdoc')} > to > ('Aslib','ASLIB','JDOC','jdoc') Assuming you don't care what order the strings are in: r = {'a':('ASLIB','Aslib'),'j':('JDOC','jdoc')} result = sum(r.values(), ()) If you do care about the order: r = {'a':('ASLIB','Aslib'),'j':('JDOC','jdoc')} keys = r.keys() keys.sort() result = [] for key in keys: result.extend(r[key]) result = tuple(result) -- Steven. From steve at holdenweb.com Mon Nov 13 04:42:53 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Nov 2006 03:42:53 -0600 Subject: reduce to be removed? In-Reply-To: <1163314554.972785.175860@h48g2000cwc.googlegroups.com> References: <1163283012.372607.185510@m73g2000cwd.googlegroups.com> <1163285443.536672.289940@m73g2000cwd.googlegroups.com> <1163314554.972785.175860@h48g2000cwc.googlegroups.com> Message-ID: Paddy wrote: > Dustan wrote: > >> Anyway, I figured out a way to get the builtin >> function 'sum' to work as I need: >> sum([[1,2,3],[4,5,6],[7,8,9]], []) >> > > Hah! > No-one expects sum to be used on anything but numbers. > > Except lists as above. > > No-one expects sum to be used on anything but numbers, and maybe lists > too. > > ;-) [voice mumbles:] "What about tuples" Right, tuples too. But apart from tuples and lists, nobody expects sum to be used on anything but numbers. In actual fact when Alex Martelli introduced sum() he intended it to be polymorphic over all the container types including strings. The check to exclude the string case was added when it was determined that it was terribly inefficient to concatenate strings that way. the same may well apply to other sequences. I suppose it's only a matter of time before someone wants to define dict.__add__ ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From robert.kern at gmail.com Fri Nov 17 13:57:31 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 17 Nov 2006 12:57:31 -0600 Subject: What python modules are available? In-Reply-To: References: <1163765733.745577.116670@m73g2000cwd.googlegroups.com> <1163767023.599564.260920@m7g2000cwm.googlegroups.com> Message-ID: km wrote: > Hi all, > > Thats ridiculous! why is that the numpy implementation documentation is > put on sale and not available freely to everyone? http://www.tramy.us/FAQ.html In brief, because otherwise there wouldn't be any complete documentation. With all due respect to the Numeric manual's authors, it was never complete and occasionally inaccurate over its lifetime. Time is not free. On the other hand, if you are willing to put your time where your demanding mouth is, the community would appreciate your efforts in expanding the freely available documentation: http://www.scipy.org/Documentation -- 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 mytempmailid at gmail.com Thu Nov 16 20:33:59 2006 From: mytempmailid at gmail.com (PS) Date: Thu, 16 Nov 2006 17:33:59 -0800 Subject: Printing/writing an integer to a file Message-ID: <220f22820611161733w7db0d3a0mb53d888cd704dbc4@mail.gmail.com> Friends, I am new to python and did search on the web on how to achieve this: ( I am trying to append the line numbers to all the lines of a file for now) Thanks!! ================================================= import os, sys fileName = os.path.join("C:", "temp", "x1.txt") fileobject = open(fileName, 'r') outputDir = "C://temp//" linenumber = 0 fileName1 = outputDir + "x2.txt" fileobject1 = open(fileName1, 'w') while (1): L = fileobject.readline() if L=="": print "**Done" break linenumber += 1 fileobject1.write(ln) fileobject1.write(":: "+ L) fileobject1.close() ============================================================= -- Regards, Prem -------------- next part -------------- An HTML attachment was scrubbed... URL: From fang.fang2003 at gmail.com Thu Nov 30 12:17:01 2006 From: fang.fang2003 at gmail.com (Grace Fang) Date: 30 Nov 2006 09:17:01 -0800 Subject: extremely slow array indexing? Message-ID: <1164907021.765969.129280@80g2000cwy.googlegroups.com> Hi, I am writing code to sort the columns according to the sum of each column. The dataset is huge (50k rows x 300k cols), so i need to read line by line and do the summation to avoid the out-of-memory problem. But I don't know why it runs very slow, and part of the code is as follows. I suspect it's because of array index, but not sure. Can anyone point out what needs to be modified to make it run fast? thanks in advance! ... from numpy import * ... currSum = zeros(self.componentcount) currRow = zeros(self.componentcount) for featureDict in self.featureDictList: currRow[:] = 0 for components in self.componentdict1: if featureDict.has_key(components): col = self.componentdict1[components] value = featureDict[components] currRow[col]=value; currSum = currSum + row; ... From nick at craig-wood.com Fri Nov 17 11:30:04 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 17 Nov 2006 10:30:04 -0600 Subject: pyserial port connection problem References: <1163764748.744393.130660@m7g2000cwm.googlegroups.com> Message-ID: Jon wrote: > I wrote some code to read in info from a port using pyserial. the code > reads info sent by a box that is connected to my computer by an > rs232-to usb adapter. When I was writing the code and testing it on my > computer it worked fine. > I ran py2exe on the program (which uses wxpython for its gui) and sent > the output from the py2exe to another computer. now when I try to run > it on this other computer it fails to open the port. it gives the error > that it cannot createfile. the code I'm using to connect is the same as > it is when it worked on my computer. > I do notice that pyserial sees this port on the other computer as > \\\\.\\COM14 - while windows device manager displays it as COM14. That is a bit too many backslashes... You can only directly open COM1 to COM9 under windows. If you have >= 10 COM ports you need to use the \\.\COM14 syntax. It looks like your backslashes have been doubled somewhere along the line, though this maybe be a printing artifact. Are you passing the port name into pyserial or allowing the user to choose it, or just getting pyserial to choose the n-th port? Also are you running as adminstrator? You may need admin rights to open a serial port under windows (I'm not sure). -- Nick Craig-Wood -- http://www.craig-wood.com/nick From rtw at freenet.co.uk Sun Nov 5 14:48:57 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sun, 05 Nov 2006 13:48:57 -0600 Subject: How to get/read Hard disk label / drive label References: <1162752076.121514.313750@h48g2000cwc.googlegroups.com> Message-ID: Praveen wrote in news:1162752076.121514.313750 @h48g2000cwc.googlegroups.com in comp.lang.python: > I want to read individual disk label > > for Hard disk (C: drive, D: drive disk label) > and > CD-ROM disk label > > Please provide some pointer to the code or document. > You could use: which will require: http://sourceforge.net/projects/pywin32/ Or you can use this: http://windowssdk.msdn.microsoft.com/en-us/library/ms685899.aspx with this: http://docs.python.org/dev/lib/module-ctypes.html which is built in to python 2.5 Rob. -- http://www.victim-prime.dsl.pipex.com/ From shansen at advpubtech.com Thu Nov 23 18:25:35 2006 From: shansen at advpubtech.com (Stephen Hansen) Date: Thu, 23 Nov 2006 15:25:35 -0800 Subject: The Python Papers Edition One In-Reply-To: <1164323350.988946.209350@l12g2000cwl.googlegroups.com> References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <7xodqyn5kd.fsf@ruckus.brouhaha.com> <1164323350.988946.209350@l12g2000cwl.googlegroups.com> Message-ID: <7a9c25c20611231525r1033ab38ydc70a9f893bac1c@mail.gmail.com> > Perhaps people could comment on the following proposition -- if an > organisation is Not for Profit, its dealings are therefore > Noncommercial? I think the problem is Python has historically been so very free-- It has always been *extremely* Business-Friendly, and totally lacks ... ah, the moral opposition to how a closed-source business wants to run their own lives. :) Consider this: my company is makes a product written mostly in Python. It's commercial and closed-source. If content from the papers ended up in the python documentation website, it might just end up in the Python docs themselves.... And I distribute python for commercial purposes :) As do a lot of people... therefore, everything in the python distribution-- code, docs, etc-- has to be able to be distributed for commercial purposes. I am SO not a lawyer. But remember, the Python-developers and Python.org are not the only people who "distribute" Python and what's in it... I do too. Others do too. So nothing can end up in Python that I can't freely distribute. That's not to say they couldn't link to your content and not-include it in any downloads or anything. Then it'd be available to anyone on-the-website and such. Also it's not saying you SHOULD change your license. I don't know if a journal and its articles would be the kind of thing that WOULD make it into core-Python-documentation in general... It's articles-- possibly interesting and useful ones, but docs tend to be more referency... and if it would make it into the docs? You can always relicense anything you hold :) --Ix -------------- next part -------------- An HTML attachment was scrubbed... URL: From allenjo5 at mail.northgrum.com Tue Nov 21 15:22:06 2006 From: allenjo5 at mail.northgrum.com (allenjo5 at mail.northgrum.com) Date: 21 Nov 2006 12:22:06 -0800 Subject: Question about unreasonable slowness In-Reply-To: <1164126305.682178.207780@j44g2000cwa.googlegroups.com> References: <1163709918.739398.194880@b28g2000cwb.googlegroups.com> <455ce05a$0$5794$4d3efbfe@news.sover.net> <1163773005.201111.175020@f16g2000cwb.googlegroups.com> <1163795956.923263.200590@e3g2000cwe.googlegroups.com> <1164126305.682178.207780@j44g2000cwa.googlegroups.com> Message-ID: <1164140526.333378.168260@j44g2000cwa.googlegroups.com> allenjo5 at mail.northgrum.com wrote: > James Antill wrote: > > On Fri, 17 Nov 2006 12:39:16 -0800, allenjo5 wrote: > > > > >> allenjo5 at mail.northgrum.com: > > >> > Ok, I built Python 2.5 (same AIX 5.1 machine). With the "for line in > > >> > shellOut" loop in, it now takes "only" 7 secs instead of the 11 secs in > > >> > python 2.4.3. So, that's better, but still unreasonably slow. And to > > >> > answer another's question, I'm using the ksh builtin 'time' command to > > >> > time the overall script. > > >> > > > >> > BTW, I don't think the AIX /bin/sh (actually ksh) is inherently slow. > > >> > This naively translated pure shell version of my python test script > > >> > completes in .1 secs: > > >> > > > >> > i=1 > > >> > while ((i<20)) > > >> > do ((i+=1)) > > >> > print next > > >> > print "$shellIn" | /bin/sh -c ':' | > > >> > while read line > > >> > do print $line > > >> > done > > >> > done > > >> > > > Yeah, apparently this is an AIX specific issue - perhaps the python > > > implementation of popen4() needs to do something special for AIX? > > > > This seems likely a more general issue, rather than just a python issue > > (although the huge speed up from moving to 2.5.x). A > > couple of things I'd try: > > With help from c.u.aix, I've discovered the problem. Python (in > popen2.py) is attempting to close filedescriptors 3 through 32767 > before running the /bin/sh. This is because os.sysconf('SC_OPEN_MAX') > is returning 32767. So far, it looks like SC_OPEN_MAX is being set > correctly to 4 in posixmodule.c, and indeed, os.sysconf_names seems to > also have SC_OPEN_MAX set to 4: > > python -c 'import os; print os.sysconf_names' > > ... > 'SC_XOPEN_XCU_VERSION': 109, 'SC_OPEN_MAX': 4, 'SC_PRIORITIZED_IO': 91, > ... > > In fact, none of the values that sysconf_names has set for the various > constants are being returned by os.sysconf(). For example, the 2 > others I just listed: > > $ ./python -c 'import os; print os.sysconf("SC_XOPEN_XCU_VERSION")' > 4 > > $ ./python -c 'import os; print os.sysconf("SC_PRIORITIZED_IO")' > -1 > > This makes no sense to me... unless there is some memory alignment or > endian issue going on here? More info: clearly I had no idea what I was talking about :-) The numbers associated with the names returned by os.sysconf_names are the indices to an array that the C sysconf() function uses to return the value of the name. So, the fact that os.sysconf("SC_OPEN_MAX") was returning 32767 on AIX is correct. However, the slowness this causes is still an issue. This is because python is closing all these file descriptors in python code, not C code - specifically, in popen2.py: try: MAXFD = os.sysconf('SC_OPEN_MAX') except (AttributeError, ValueError): MAXFD = 256 ... def _run_child(self, cmd): if isinstance(cmd, basestring): cmd = ['/bin/sh', '-c', cmd] for i in range(3, MAXFD): try: os.close(i) except OSError: pass try: os.execvp(cmd[0], cmd) finally: os._exit(1) Any chance the "for i in range(3, MAXFD):" loop could be done in C instead? Even having, say, an os.rclose(x,y) low level function to close all file descriptors in range [x,y] would be great. John. From struggle at mail.nankai.edu.cn Mon Nov 20 03:07:11 2006 From: struggle at mail.nankai.edu.cn (Bo Yang) Date: Mon, 20 Nov 2006 16:07:11 +0800 Subject: How to do multivolume zip in python? Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Is there any python module to do with multivolume zip? And with perl I can use CPAN to search almost all modules, How can I find a module in python efficiently? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.5 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFFYWIv7tZp58UCwyMRAj0mAJ9PdMq3Y1VMcCX2FR6DmHipqR+8/gCfeaSD mhPNFwd5zmO1DLoP4l6cJfY= =IE69 -----END PGP SIGNATURE----- From baitelli at cepel.br Tue Nov 21 14:47:43 2006 From: baitelli at cepel.br (baitelli) Date: Tue, 21 Nov 2006 19:47:43 -0000 Subject: pwinauto to remote automate a GUI ? Message-ID: Hi! pywinauto is a set of python modules to automate the Microsoft Windows GUI. With the lines below we start and atomates the apllication Notepad: from pywinauto import application app = application.Application() app.start('C:\Notepad.exe') ... pywinauto automation code Question: Is it possible to start and automate a remote GUI using Python? baitelli,r. _________________________________________________________________ AVISO Esta mensagem ? destinada exclusivamente a(s) pessoa(s) indicada(s) como destinat?rio(s), podendo conter informa??es confidenciais, protegidas por lei. A transmiss?o incorreta da mensagem n?o acarreta a perda de sua confidencialidade. Caso esta mensagem tenha sido recebida por engano, solicitamos que seja devolvida ao remetente e apagada imediatamente de seu sistema. ? vedado a qualquer pessoa que n?o seja destinat?rio, usar, revelar, distribuir ou copiar ainda que parcialmente esta mensagem. _________________________________________________________________ DISCLAIMER This message is destined exclusively to the intended receiver. It may contain confidential or legally protected information. The incorrect transmission of this message does not mean loss of its confidentiality. If this message is received by mistake, please send it back to the sender and delete it from your system immediately. It is forbidden to any person who is not the intended receiver to use, reveal, distribute, or copy any part of this message. _________________________________________________________________ From steve at REMOVE.THIS.cybersource.com.au Sat Nov 18 18:21:10 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 19 Nov 2006 10:21:10 +1100 Subject: decompiler References: <1163864577.987875.64990@m7g2000cwm.googlegroups.com> Message-ID: On Sat, 18 Nov 2006 07:42:58 -0800, jim wrote: > where can I find a free decompile that I can run in windows xp Here: http://catb.org/esr/faqs/smart-questions.html -- Steven. From gagsl-py at yahoo.com.ar Mon Nov 13 21:36:36 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 13 Nov 2006 23:36:36 -0300 Subject: Unpacking sequences and keywords in one function call In-Reply-To: <1163466377.919531.113560@h54g2000cwb.googlegroups.com> References: <1163466377.919531.113560@h54g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061113233121.039dcc38@yahoo.com.ar> At Monday 13/11/2006 22:06, ram wrote: >Stupid question #983098403: > >I can't seem to pass an unpacked sequence and keyword arguments to a >function at the same time. What am I doing wrong? > >def f(*args, **kw): > for a in args: > print 'arg:', a > for (k,v) in kw.iteritems(): > print k, '=', v > > >>> f(1,2) >arg: 1 >arg: 2 > > >>> f(*[1,2]) >arg: 1 >arg: 2 > > >>> f(1,2, a=1) >arg: 1 >arg: 2 >a = 1 > > >>> f(*[1,2], a=1) > File "", line 1 > f(*[1,2], a=1) > ^ > SyntaxError: invalid syntax Reverse the order: f(a=1, *[1,2]) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From kinch1967 at gmail.com Tue Nov 28 21:55:57 2006 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 28 Nov 2006 18:55:57 -0800 Subject: 6 Pick Bet Grouping Message-ID: <1164768957.528355.210070@16g2000cwy.googlegroups.com> (I apologise in advance for posting something slightly OT, but plead in mitigation that I'm trying to re-write an old, suboptimal VB6 (erk) brute-force attack in a shiny, elegant, pythonic manner. I would really appreciate some ideas about an appropriate algorithmic approach to this + pointers to any relevant implementations in Python. Along the way, I'm also trying to get Python into my organisation through the back door - so a further plea for tolerance in posting this here! :)) A single 6 Pick bet looks like this: RACE1 RACE2 RACE3 RACE4 RACE5 RACE6 runner1 / runner 2 / runner 3 / runner4 / runner5 / runner6 - $amount e.g. we might have: 5 / 3 / 11 / 7 / 1 / 9 - $50 (5 to come 1st or 2nd in Race1, 3 to come first or 2nd in Race 2, etc.) 7 / 3 / 11 / 7 / 1 / 9 - $50 5 / 3 / 11 / 14 / 1 / 9 - $50 7 / 3 / 11 / 14 / 1 / 9 - $50 The totalizator system allows us to merge or group these four bets as follows: 5 + 7 / 3 / 11 / 7 + 14 / 1 / 9 - $50 ($200 total) This method of expressing multiple bets in one line is advantageous because we may have many thousands of combinations we wish to bet and only a limited amount of time in which to bet them. There are up to 14 horses in each race, so 7,529,536 possible 6 Pick bets. In practice, one might wish to bet (say)15,000 combinations out of these 7.5 million. However, it would be very nice to be able to *optimally* merge (as shown above) these 15,000 combinations so that they might fit on (say) 2,000 betting tickets instead of trying to write out 15,000 single tickets. To keep things simple, let's assume that all single bets are for the same amount. (In practice, however, this is not so.) Now, it's certainly possible to go about this via brute force iteration, but I would really appreciate it if anyone with a CS background could point me toward a smarter plan of attack. I have perused Skiena's Algorithm Handbook and various websites and can't seem to find an analogous problem. I'm hoping this is just my ignorance and that my brief exposition rings a bell for someone here. From mike at hobbshouse.org Mon Nov 13 12:20:12 2006 From: mike at hobbshouse.org (Michael Hobbs) Date: Mon, 13 Nov 2006 11:20:12 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <4554D416.70408@hobbshouse.org> Message-ID: <4558A94C.9040002@hobbshouse.org> Steven D'Aprano wrote: > On Fri, 10 Nov 2006 15:18:55 -0600, Michael Hobbs wrote: > > >> Ron Adam wrote: >> >>> It is also an outline form that frequently used in written languages. Something >>> python tries to do, is to be readable as if it were written in plain language >>> where it is practical to do so. So the colon/outline form makes a certain sense >>> in that case as well. >>> >>> >> That is perhaps the most convincing argument that I've heard so far. >> Indeed, I often find myself writing out colons when writing pseudo-code >> out on paper. The reason, however, is usually because my indents don't >> quite line up as perfectly on paper as they do in an editor. The colons >> provide a form of backup separation for when my columns start to get >> sloppy. (Natural language is actually filled with such redundancies in >> order to compensate for sloppy handwriting.) >> > > Er, natural language pre-dates handwriting by many tens or hundreds of > thousands of years. The redundancy of natural language has many reasons, > but compensating for sloppy handwriting is not one of them. I was using the term "natural language" in a wider sense, as in spoken languages, unspoken languages (sign languages), and writing systems. As far redundancies in writing systems go, it has been estimated that there is ~50% redundancy in the characters alone. That is, you can usually determine what a character is even when half of its strokes are removed. That's not even considering other redundancies such as using a phonetic alphabet vs. ideographs, or writing the vowels between consonants, which only started with the Greek alphabet. >> This backup function >> obviously isn't needed when a computer is taking care of the layout. >> > > That word you use, "obviously", I don't think it means what you think it > means. There's nothing obvious about your conclusion to me. > > while (this really long expression > (which extends over multiple lines > and contains many statements) > some of which (like this one) contain > nested bracketed terms such as (this > expression here) but like all good > things) it eventually ends > and we can get to the business > of executing the while-block > > Compare that to the version with a colon: > > while (this really long expression > (which extends over multiple lines > and contains many statements) > some of which (like this one) contain > nested bracketed terms such as (this > expression here) but like all good > things) it eventually ends: > and we can get to the business > of executing the while-block > > > Arguably, the parser might not find the first version any more difficult > than the second, but I know which one I'd rather read. I'd rather read neither. Both of them are obviously illegible. As the saying goes, you can write FORTRAN code in any language. That is, no language, no matter what its parsing rules, can prevent you from writing illegible code if you're determined to do so. To me, the second example is no more legible simply because it contains a colon somewhere. Proper style would dictate that you make some form of obvious break when writing a multi-line conditional, no matter which language you're using. Some possibilities: while (this really long expression (which extends over multiple lines and contains many statements) some of which (like this one) contain nested bracketed terms such as (this expression here) but like all good things) it eventually ends: and we can get to the business of executing the while-block or while (this really long expression (which extends over multiple lines and contains many statements) some of which (like this one) contain nested bracketed terms such as (this expression here) but like all good things) it eventually ends: and we can get to the business of executing the while-block or while (this really long expression (which extends over multiple lines and contains many statements) some of which (like this one) contain nested bracketed terms such as (this expression here) but like all good things) it eventually ends: #### BODY #### and we can get to the business of executing the while-block >> My final argument against the colons is to simply try programming in >> Ruby for a while and then come back to Python. I think you'll find that >> programming without the colons just simply feels more "natural". >> > > And maybe you're even correct. But one major reason of using the colon is > to make it easier for _inexperienced_ programmers. Your suggestion that > programming in Ruby for a while should be a prerequisite for making Python > easy to read is an interesting one, but not one that many people will > agree with. *wink* Is Python a cult, where it's considered dangerous to experience the outside world out of fear that it may corrupt your mind and make you question all sorts of long-standing edicts? If you're concerned about coddling inexperienced programmers, maybe you should join Java cult. I hear that it is much more "safe" ;-) - Mike From gagsl-py at yahoo.com.ar Tue Nov 7 17:09:32 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 07 Nov 2006 19:09:32 -0300 Subject: C wrapper In-Reply-To: <1162932189.315088.58420@m7g2000cwm.googlegroups.com> References: <1162928252.643092.23350@h48g2000cwc.googlegroups.com> <1162930226.658619.79830@m73g2000cwd.googlegroups.com> <1162932189.315088.58420@m7g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20061107184948.03f3de38@yahoo.com.ar> At Tuesday 7/11/2006 17:43, Sheldon wrote: > > And what are those non-static functions used for? The *only* purpose > > of your module should be to provide the Python bindings... > >I wrote the C module to do some number crunching. Now I just need to >"connect" it to my python program. Should the initmsgpps_functions() be >the only function in the file? Then how do I "connect" my C module to >my Python program? Read again the docs but have in mind that you are *extending* the interpreter with a new module - disregard the references to *embedding* Python (even if they appear in a section about extending!). I can see your confusion reading http://docs.python.org/ext/methodTable.html That is, you *don't* write a main() function, and you *don't* invoke Py_Initialize; just write your initXXX() function. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From ananyablr at gmail.com Tue Nov 21 05:07:36 2006 From: ananyablr at gmail.com (comp.lang.python) Date: 21 Nov 2006 02:07:36 -0800 Subject: how to call user defined TCL procedures from python script? Message-ID: <1164103655.930495.306850@h48g2000cwc.googlegroups.com> Hi, I am using some TCL driver APIs and user define TCL function to control a traffic generator. The APIs are the traffic generator's specific and in built to the driver library. The issue is calling API and user define TCL functions from python script. I am looking for the way to include user define TCL lib to python script and call those user define functions from python script. thanks & regards ananya From nyamatongwe+thunder at gmail.com Wed Nov 1 17:01:35 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 01 Nov 2006 22:01:35 GMT Subject: uninstall and Windows file associations In-Reply-To: <1162414083.490714.313860@e3g2000cwe.googlegroups.com> References: <1162414083.490714.313860@e3g2000cwe.googlegroups.com> Message-ID: <3P82h.57160$rP1.14468@news-server.bigpond.net.au> Roger Miller: > When I installed Python 2.5 (on Windows XP) I left 2.4 in place "just > in case". Today I decided to remove it. However after doing so (from > the control panel) I found that Windows no longer knows about the > Python file types and associations. Is this behavior expected, This is pretty much inevitable on Windows as there is no generic support to handle this sort of situation. Python could attempt to do its own special case handling (with a registered list of Python installations and an arbitration/repair phase in the uninstaller) but it would be a lot of work and quite fragile. Just reinstall your preferred version. You may want to check which extensions have been installed into Python so that they can also be reinstalled if needed. Neil From desale at india.com Wed Nov 22 23:52:18 2006 From: desale at india.com (sandip desale) Date: Thu, 23 Nov 2006 12:52:18 +0800 Subject: Porting Tkinter application to JYthon Message-ID: <20061123045218.BFAF8CA0A4@ws5-11.us4.outblaze.com> Dear All, We have a Tcl/Tk application written using Python 2.2. Using this application we want to call some customizable Java APIs. I tried porting Tcl/Tk application to Jython but not able to do the same as TKinter library is not available with JYthon. Can you please help me in porting Tkinter application to Jython? Also kindly let me know how to do the same. Thanks & Regards, Sandip Desale -- Search for products and services at: http://search.mail.com From fredrik at pythonware.com Fri Nov 17 02:08:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 17 Nov 2006 08:08:33 +0100 Subject: Python v PHP: fair comparison? In-Reply-To: <1163715688.959899.65990@h48g2000cwc.googlegroups.com> References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> <1163681949.338244.323390@k70g2000cwa.googlegroups.com> <1163715688.959899.65990@h48g2000cwc.googlegroups.com> Message-ID: sjdevnull at yahoo.com wrote: > Huh? I've been doing paid python web work since 2000. I'm fairly sure > that Yahoo! groups predates that by a while http://en.wikipedia.org/wiki/EGroups From anton.vredegoor at gmail.com Fri Nov 24 09:44:45 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 24 Nov 2006 15:44:45 +0100 Subject: How do I access a main frunction from an import module? In-Reply-To: <1164377547.562483.152770@l12g2000cwl.googlegroups.com> References: <1164377547.562483.152770@l12g2000cwl.googlegroups.com> Message-ID: Jim wrote: > I have created an import module. And would like to access a function > from the main script, e.g., > > file abc.py: > ################### > def a(): > m() > return None > #################### > > file main.py: > ##################### > from abc import * > def m(): > print 'something' > return None > > a() import sys def a(): sys.modules['__main__'].m() return None Anton 'now why would anyone want to do *that* ?' From pavlovevidence at gmail.com Mon Nov 27 10:21:17 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 27 Nov 2006 07:21:17 -0800 Subject: Inheritance from builtin list and override of methods. References: <200611261804.54669.mgiann@beta-cae.gr> Message-ID: <1164640877.138870.206320@14g2000cws.googlegroups.com> Fredrik Lundh wrote: > Michalis Giannakidis wrote: > > > Could someone please explain the reasoning/behabiour of these? > > in general, methods on C objects are implemented in terms of operations > on the internal data structures, not in terms of a subset of the methods > already provided by the object. True, and it's also true for many Python classes. Here's a very silly example: class Cons(object): def __init__(self,car,cdr): self.car = car self.cdr = cdr def __getitem__(self,key): if key == "car": return self.car if key == "cdr": return self.cdr raise KeyError(key) def __getitem__(self,key,value): if key == "car": self.car = value if key == "cdr": self.cdr = value raise KeyError(key) def swap(self): self.car,self.cdr = self.cdr,self.car So hooking into __getitem__ and __setitem__ won't let you inpect the swap operation. It's much the same with lists: they bypass __getitem__ and __setitem__ and go directly to their internal. OTOH, I've written a few C types that deliberately go though slower Python methods to allow overriding. But that has to be deliberate (for the most part); as Frederick said, most C classes don't do that. Carl Banks From noah.rawlins at comcast.net Sun Nov 19 19:59:45 2006 From: noah.rawlins at comcast.net (Noah Rawlins) Date: Sun, 19 Nov 2006 19:59:45 -0500 Subject: re.match -- not greedy? In-Reply-To: <1163981503.295521.7180@m7g2000cwm.googlegroups.com> References: <1163981503.295521.7180@m7g2000cwm.googlegroups.com> Message-ID: Carl Banks wrote: > EXI-Andrews, Jack wrote: >> the '*' and '+' don't seem to be greedy.. they will consume less in >> order to match a string: >> >>>>> import re;re.match('(a+)(ab)','aaab').groups() >> ('aa', 'ab') >> >> this is the sort of behaviour i'd expect from >> '(a+?)(ab)' >> >> a+ should greedily consume a's at the expense of the string not matching > > It's called backtracking. If a match fails, the regexp engine > recursively unwinds some of the greedy matching and tries again. > >> in real life, i am trying to match #defines: >> >>>>> re.match( '#define ([A-Za-z0-9_]+)([^(])', '#define >> abc(d)').groups() >> ('ab', 'c') >> >> i want this example to fail because the first character after a string >> of letters is a '(' >> i want to match only #defines without parameters. > > Probably the easiest thing to do is to attempt to match zero or one > opening parentheses, and bail out if it did end up matching the > parenthesis. > > m = re.match(r"#define ([A-Za-z0-9_]+)(\(?)","#define abc(d)") > if m and m.groups(2) != "(": > ... > > (BTW, it's good practice to use a raw strings for the regular > expressions as I did.) > Another way that seems clearer to me is to use negative lookahead assertions. >>>defPatt = re.compile(r'#define\s+(\w+)\b(?!\()') >>> defPatt.match("#define abc(x)") >>> defPatt.match("#define foo_BarBaz") <_sre.SRE_Match object at 0xb7dd5820> >>> defPatt.match("#define foo_BarBaz").groups() ('foo_BarBaz',) In general '\w' is the same as [A-Za-z0-9_] There are other considerations too... I don't know if #define abc (x) But the main thing here is the use of '\b' to require there to be a word boundary at the end your match and a (?!\() to require that the match is not followed by a '(' see http://docs.python.org/lib/re-syntax.html noah >> so what's the definition of greedy? > > It means match as much you can *while getting a match*. > > Just remember regexp parsing is not a one way street: if it hits a dead > end, it'll go back and try another path. In fact, greediness usually > doesn't affect *whether* a regexp matches; it only affects the > groupings. I'm suddenly curious if there are any cases at all where > greediness changes whether it finds a match. > >> (pls copy me on responses) > > Ah, too bad you won't see it then.... > > > Carl Banks > From nogradi at gmail.com Wed Nov 22 09:20:53 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 22 Nov 2006 15:20:53 +0100 Subject: text file parsing (awk -> python) In-Reply-To: References: Message-ID: <5f56302b0611220620o77583ac3xb740ac3ce59d09a5@mail.gmail.com> > > I have an awk program that parses a text file which I would like to > > rewrite in python. The text file has multi-line records separated by > > empty lines and each single-line field has two subfields: > > > > node 10 > > x -1 > > y 1 > > > > node 11 > > x -2 > > y 1 > > > > node 12 > > x -3 > > y 1 > > > > and this I would like to parse into a list of dictionaries like so: > > > > mydict[0] = { 'node':10, 'x':-1, 'y':1 } > > mydict[1] = { 'node':11, 'x':-2, 'y':1 } > > mydict[2] = { 'node':12, 'x':-3', 'y':1 } > > > > But the names of the fields (node, x, y) keeps changing from file to > > file, even their number is not fixed, sometimes it is (node, x, y, z). > > > > What would be the simples way to do this? > > data = """node 10 > x -1 > y 1 > > node 11 > x -2 > y 1 > > node 12 > x -3 > y 1 > """ > > def open(filename): > from cStringIO import StringIO > return StringIO(data) > > converters = dict( > x=int, > y=int > ) > > def name_value(line): > name, value = line.split(None, 1) > return name, converters.get(name, str.rstrip)(value) > > if __name__ == "__main__": > from itertools import groupby > records = [] > > for empty, record in groupby(open("records.txt"), key=str.isspace): > if not empty: > records.append(dict(name_value(line) for line in record)) > > import pprint > pprint.pprint(records) Thanks very much, that's exactly what I had in mind. Thanks again, Daniel From john at castleamber.com Thu Nov 16 12:30:29 2006 From: john at castleamber.com (John Bokma) Date: 16 Nov 2006 17:30:29 GMT Subject: Python v PHP: fair comparison? References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <1163559359.010787.185840@m73g2000cwd.googlegroups.com> <1163681949.338244.323390@k70g2000cwa.googlegroups.com> <1163697632.352189.110920@h54g2000cwb.googlegroups.com> Message-ID: "Luis M. Gonz?lez" wrote: > > Fredrik Lundh ha escrito: > >> Luis M. Gonz?lez wrote: >> >> > But as a web development language, it's olnly when people started >> > to look for the "rails killer" and many python alternatives started >> > to come up (although Django has been in development for a long time >> > before all this hype). >> >> nah, people have built web stuff on Python for as long as we've had a >> web. >> >> > > I know, but would you consider a python cgi application a good > competence against php? php running as cgi you mean. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From greg.kujawa at gmail.com Wed Nov 29 14:45:18 2006 From: greg.kujawa at gmail.com (gregarican) Date: 29 Nov 2006 11:45:18 -0800 Subject: why would anyone use python when java is there? References: <1164762232.220759.57160@h54g2000cwb.googlegroups.com> <1164764454.043697.125730@j72g2000cwa.googlegroups.com> <1164818505.696250.264070@h54g2000cwb.googlegroups.com> Message-ID: <1164829518.865155.60720@l39g2000cwd.googlegroups.com> He trolls other groups as well. Smalltalk for example --> http://groups.google.com/group/comp.lang.smalltalk/browse_thread/thread/1c83e576be824633/927227555661a2cd?lnk=gst&q=gavino&rnum=1#927227555661a2cd. There are at least a dozen recent posts where he asks some obvious trollling line of questioning... Adam Jones wrote: > gregarican wrote: > > gavino wrote: > > > wtf > > > > You have to be trolling I would think. > > Yeah, gavino has been trolling comp.lang.lisp for quite some time. For > the life of me I can't understand why he would troll comp.lang.python > when comp.lang.lisp is there. > > -Adam From srikrishnamohan at gmail.com Wed Nov 15 17:04:58 2006 From: srikrishnamohan at gmail.com (km) Date: Thu, 16 Nov 2006 03:34:58 +0530 Subject: java python GPL Message-ID: Hi all, what does Java released under GPL mean to python ? could it hamper python development on the long run? regards, KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From pieterswart at comcast.net Sat Nov 25 23:49:55 2006 From: pieterswart at comcast.net (Pieter Swart) Date: 25 Nov 2006 20:49:55 -0800 Subject: Graph Data Structures In-Reply-To: References: Message-ID: <1164516595.141919.29580@h54g2000cwb.googlegroups.com> Nathan Harmston wrote: > Currently I am working on a generic graph library so I can do various > graph based analysis for various projects I have ideas for. Currently > I am implementing Graph as a wrapper around a dictionary. Currently my > implementation works like this: > > t = Graph() > n1 = Node("Node1") > n2 = Node("Test2") > edge1 = Edge("Test3") > t += n1 { n1:{}} > t[n1][n2] = edge1 { n1:{n2:edge1} > > However this isnt actually ending up with the structure I want. I want > it to finally end up as ...... { n1:{n2:edge1}, n2:{}}. Is > there anyway I can do this simply???? Nathan By now you probably discovered that the networkx package can handle this. If I have this right, you want to create a digraph with a directed edge from "Node1" to "Node2" and this edge has the string "Test3" attached to it. In networkx, this is exacty what the XDiGraph class was designed to do. Here DiGraph means directed graph and the X means you are allowed to add (any) data to the edge,for example: >>> import networkx as nx >>> t = nx.XDiGraph() >>> t.add_edge( "Node1", "Node2", "Test3") > Also I am looking at having a large graph and was wondering if anyone > knew of anyway I could reduce the memory requirements of this > structure and improve the speed of queries on it. I m thinking writing > a C extension for it....is this a good idea and where would I start? > Or does Python have some kind of transparent memory access module I > can implement. > Networkx was designed so that you can hook your own C extension in. However, making it ispeed or memory efficient is quite application dependent. I am still not clear as to exactly what class of algorithms you want to implement via a string-interval representation, and whether you demand exact alignment or whether missing/incorrect data etc. is allowed as part of the alignment problem. HTH Pieter Swart From python-ml at nn7.de Fri Nov 24 05:11:06 2006 From: python-ml at nn7.de (Soeren Sonnenburg) Date: Fri, 24 Nov 2006 10:11:06 +0000 (UTC) Subject: bz2.readline() slow ? Message-ID: Dear all, I am a bit puzzled, as -----snip----- import bz2 f=bz2.BZ2File('data/data.bz2'); while f.readline(): pass -----snip----- takes twice the time (10 seconds) to read/decode a bz2 file compared to -----snip----- import bz2 f=bz2.BZ2File('data/data.bz2'); x=f.readlines() -----snip----- (5 seconds). This is even more strange as the help(bz2) says: | readlines(...) | readlines([size]) -> list | | Call readline() repeatedly and return a list of lines read. | The optional size argument, if given, is an approximate bound on the | total number of bytes in the lines returned. This happens on python2.3 - python2.5 and it does not help to specify a maximum line size. Any ideas ? Soeren From http Thu Nov 16 05:44:30 2006 From: http (Paul Rubin) Date: 16 Nov 2006 02:44:30 -0800 Subject: Decimal() instead of float? References: <1163294604.4675.4.camel@pepper> <1163322853.760315.51040@k70g2000cwa.googlegroups.com> <455b82a0$0$7054$c3e8da3@news.astraweb.com> Message-ID: <7xhcwzy8kx.fsf@ruckus.brouhaha.com> Steve Holden writes: > Unfortunately some applications are getting such large tables that a > 32-bit field is insufficient to enumerate all existing and deleted > rows. Then you have to start keeping tables of unused primary keys. Please tell me that's not from some Kafka nightmare. They don't use 64-bit ints? From jcoleman at franciscan.edu Thu Nov 2 16:29:57 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 2 Nov 2006 13:29:57 -0800 Subject: Python in sci/tech applications In-Reply-To: References: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> <1162489638.013433.102180@h48g2000cwc.googlegroups.com> <1162491753.605134.162700@i42g2000cwa.googlegroups.com> Message-ID: <1162502997.175322.171730@e3g2000cwe.googlegroups.com> Maybe I don't know what I'm looking for, but I downloaded Enthought a few days ago and don't seem to find MinGW on my system. There are 2 relatively small (totalling about 13 kb IIRC) *python* files deeply buried in the distribution with mingw in their filename but nothing like a gcc compiler. I've mostly used visual studio or code warrior for C compiling, so again - maybe I don't know what I am looking for. -John Coleman p.s. Pretty cool sig line - the older I get, the more enigmatic the world seems. I appreciate all of the effort that Enthought puts into their distribution. Robert Kern wrote: > Steve Holden wrote: > > Robert Kern wrote: > >> bearophileHUGS at lycos.com wrote: > >> > >>> Robert Kern: > >>> > >>>> We distribute mingw set up to do this with our "Enthought > >>>> Edition" Python distribution. > >>>> http://code.enthought.com/enthon/ > >>> Sorry, maybe I'm blind but I don't see MinGW listed in that page... > >>> Maybe it's included but not listed... > >> > >> It's there. > >> > > Well I tend to believe you, but Firefox is calling you a liar: a search > > fails at "min". > > Sorry, by "it's there" I meant "it is actually included in the distribution > regardless of any omissions on the web page." > > > Do you anticipate a 2.5-based release any time soon? > > We'll start working on it soon, at least. > > -- > 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 ptmcg at austin.rr._bogus_.com Mon Nov 20 05:26:02 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 20 Nov 2006 10:26:02 GMT Subject: trying to create a dictionary in python, using variables as a value References: <1164008459.159792.48600@k70g2000cwa.googlegroups.com> Message-ID: <_of8h.984$Gk5.315@tornado.texas.rr.com> "ronrsr" wrote in message news:1164008459.159792.48600 at k70g2000cwa.googlegroups.com... > but I keep getting syntax errors on this one - > > > > adict = {'zid': result[0][0], 'keywords': result{0][1], > 'quotations':result[0][2],'citations':result[0]{3]}; > Probably because it has some syntax errors in it. Look carefully at your "[" characters, you have typed some of them as "{". -- Paul From stefan.behnel-n05pAM at web.de Thu Nov 16 08:47:47 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 16 Nov 2006 14:47:47 +0100 Subject: lxml/ElementTree and .tail In-Reply-To: References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> <761846B7-E374-41FE-8804-CBB3D42FD4D2@snowtide.com> Message-ID: <455C6C03.5080802@web.de> Chas Emerick wrote: > the delta between Elements and DOM-style elements leads to other issues. > There's no doubt that the needed helpers are simple, but all things being > equal, not having to carry them around anywhere we're doing DOM > manipulations is a big plus. > > Because we're far from doing anything that is regular or one-off in nature. > We're systematizing the extraction of data from functionally unstructured > content, and it's flatly necessary to normalize the XHTML into something > that can be easily consumed by the processes we've built that can do that > content->data extraction/conversion from plain text, XML, PDF, and now > XHTML. > > Remember, corner cases. :-) Hmm, then I really don't get why you didn't just write a customised XHTML API on top of lxml's custom Element classes feature. Hiding XML language specific behaviour directly in the Element classes really helps in getting your code clean, especially in larger code bases. Stefan From fredrik at pythonware.com Thu Nov 23 09:17:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Nov 2006 15:17:45 +0100 Subject: "10, 20, 30" to [10, 20, 30] References: <1164280390.745628.167770@k70g2000cwa.googlegroups.com> <9afea2ac0611230335r7c987fcdw9918ef55746afe96@mail.gmail.com> Message-ID: Tim Williams wrote: >> It is a dangerous solution if your data is coming from an untrusted source. >> >> >>> s = "10, 20, 30" >> >>> L = [x.strip() for x in s.split(',')] >> >>> L >> ['10', '20', '30'] >> >>> L = [int(x) for x in L] >> >>> L >> [10, 20, 30] >> >> Or, as a one liner: [int(x.strip()) for x in s.split(',')] > > You don't need the strip() > >>>> int(' 10 ') > 10 >>>> and the use of a list comprehension is pretty silly to, given that you want to apply the same *function* to all items, and don't really need to look it up for every item: map(int, s.split(',')) From luismgz at gmail.com Tue Nov 14 21:55:59 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 14 Nov 2006 18:55:59 -0800 Subject: Python v PHP: fair comparison? In-Reply-To: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> Message-ID: <1163559359.010787.185840@m73g2000cwd.googlegroups.com> > - Python is more readable, and more general purpose Yes, php is only for web. On the other hand, Python is a general purpose language and it can be used for nearly anything you may want to do. > - PHP has awful backward compatibility Yes. And it's also an ugly language to work with. > - PHP has a lower barrier to entry I don't think it is any easier than python. Not even to begin with. > - Most inexpensive web-hosters support PHP, but not Python Sad but true. > - PHP has far more pre-writen scripts available For web projects, perhaps. But I'm sure you can do everything better with python, especially with the new crop of web frameworks (Django, Turbo Gears, etc...). > - Newer versions of mod_python require Apache 2.0, which few hosters > have You can also get alder versions of mod_python. What's the problem? > - There is more demand for PHP developers, than Python developers So you want to be a web developer? Then look no further. Learn python and go kick php developers asses in the market place. There are thousands of php developers out there. Do you want to be just one more? I'd rather learn something newer, and much more powerful. And once you get a job, you will do everything better and faster than the others, your quality will stand up from the rest and so your reputation. Then there will be more demand for "your skills". From fred at adventistcare.org Wed Nov 29 14:34:14 2006 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 29 Nov 2006 14:34:14 -0500 Subject: Python work in UK Message-ID: <1A4BF05172023E468CB6E867923BC90402B6E39E@accmail2.sunbelt.org> The technical director of Cabletron used to write applications in Python, then give the working product/code to the development group to convert. Perhaps you could build stuff in Python and outsource the conversion to India? -----Original Message----- From: python-list-bounces+frsells=adventistcare.org at python.org [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On Behalf Of Steven Wayne Sent: Friday, November 24, 2006 10:42 AM To: python-list at python.org Subject: Re: Python work in UK On Thu, 23 Nov 2006 19:28:26 +0000, Will McGugan wrote: > Hi, > > I'd love to work in Python, for the sake of my blood pressure, but there > doesnt seem to be that many jobs that look for Python as the main skill. > I use Python at work from time to time, and occasionaly get to spend > several days on a Python project but the majority of the time I use C++. > How can I make that leap to working with Python? There doesn't seem to > be many UK positions on the jobs section of Python.org or the usual jobs > sites. Any recommended jobs sites or tips? (I have googled) > > In the off chance that a potential empolyer is reading this, I'm looking > for something in web development, applications, graphics or other > interesting field. Here is a copy of my CV. > > http://www.willmcgugan.com/cvwillmcgugan.pdf > > Regards, > > Will McGugan www.riverhall.co.uk are looking. Steven -- .''`. : :' : `. `'` `- -- http://mail.python.org/mailman/listinfo/python-list From jameshcunningham at gmail.com Wed Nov 15 11:22:56 2006 From: jameshcunningham at gmail.com (James Cunningham) Date: Wed, 15 Nov 2006 11:22:56 -0500 Subject: Python v PHP: fair comparison? References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> Message-ID: <2006111511225616807-jameshcunningham@gmailcom> On 2006-11-15 10:47:07 -0500, "Demel, Jeff" said: > [...] > That's true, but I was lucky enough to find webfaction.com for python > hosting, including Django. Good prices and they know Python. I think > they used to be python-hosting.com or something. > > -Jeff Dirt-cheap Dreamhost also offers Python with Django (as well as Ruby with Rails), though I haven't used those capabilities so I can't judge how good the environment is. I suspect it isn't that great. The people at Dreamhost are great; the service itself is - at best! - unreliable. Best, James From phoolimin at gmail.com Mon Nov 20 05:42:30 2006 From: phoolimin at gmail.com (phoolimin at gmail.com) Date: 20 Nov 2006 02:42:30 -0800 Subject: Dao language 1.0 beta is release! Message-ID: <1164019350.888749.34390@e3g2000cwe.googlegroups.com> Hello, After a few months' effort, I have finished the implementation of Dao Virtual Machine(DVM), and released it as 1.0-beta. The DVM is implemented as a very efficient virtual register machine. This version has implemented all the features I have planned. Most importantly, the implementation has been switched from C++ to standard C. As a consequence, the binary code of DVM is much smaller than before (as executable 250KB, as dynamic linking library 300KB, linux/gcc4). The efficiency has also been improved as well. The structure of DVM has been changed slightly, such that the embedding and extending of DVM becomes more convinient. In fact, now the mechanism to call internal functions is exactly the same as the mechanism to call extended functions. To allow DVM being more freely used, GLPL (GNU Lesser General Public Licence) has been adopted since this release. The DVM can be compiled and run in both windows and linux, but so far, it is tested mainly under linux. As before, the documentation of Dao is not well prepared yet; and there are only a few extended modules available for using. These two things will be the prioritized work in the near future. links: website: http://www.xdao.org documentations: http://www.xdao.org/daoweb.dao?page=document ========================= Changed or new features ========================= ----- Multiple lines comment: <<<...>>> is changed to #{...#}, which can be used anywhere in the scripts. ----- Built-in functions have been organized into some basic libraries: stdlib, stdio, math, reflect, coroutine, thread etc. So now Built-in function xyz(...) should be used abc.xyz(...), where "abc" is the proper library. For convinience and efficiency, one may also do: xyz = abc.xyz; xyz(...); ----- More methods are added for basic data types; ----- Bit operations |, &, ^, ~, <<, >>; ----- Typed variables, assignment between variable of different types will issure an error: a : 1; # a is a number; not compiled virtual instruction; a := 1; # a is a number; compiled into assignment instruction; The right side of : or := must be a const. This kind of syntax is for consistence with syntax for specifying typed parameters in function definition; ----- Similarly class may have typed instance variables. Moreover, "my a := 1" will also specify the default value for the variable; ----- Class instance creation by enumeration: class MyNumber my value := 0; end num1 = MyNumber{ 123 }; num2 = MyNumber { value @= 456; # may specify the name of variables to be initialized. }; Be cautious when enumerating class members without speficying names to create class instances for derived classes. ----- Creating multi-dimensional array: changed from list = { 2, 3 } : 100; array = [ 2, 3 ] : 100; # 2 X 3 matrix to list = 100 <@> { 2, 3 }; array = 100 <@> [ 2, 3 ]; operator <@> can be called arrange operator. A<@>B, arrange A or copies of A into a list or array of shape B. If B is a list, this operator will create a new list which has shape specified by B, and contains A or copies of A as elements. If B is a numeric array, this operator will create a numeric array with shape B; if A is also a numberic array, the resulting array will contain multiple subarrays that are equal to A. This new operator is introduce because the previous using colon for multiple purpose is confusing. ----- Support coroutines similar to Lua coroutines; ----- Previous built-in functions sort(),apply(),noapply() have become methods of list or numeric array with some changing in syntax: before: sort( list, @0 < @1, n ); now: list.sort( @{ @0 < @1 }, n ); before? apply( array[ 1:5, : ], @0 + @1 * @2 ); now: array.apply( @{ @0 + @1 * @2 }, { 1:5, : } ); Expressions that are used as parameters should be put inside @{ }. The advantage for this is, simpler parsing; and moreover, they can be passed to C extending functions. =================== Extending modules: =================== New modules available: - DaoCGI: CGI web programming; - DaoFastCGI: FastCGI web programming;allow DVM to run as FastCGI server; - DaoSqlite: binding to Sqlite3 database; lighttpd +sqlite +dao could be a good option for some websites, since each of them is designed to be light and efficient. - DaoOpenGL: 3D graphics; support upto DaoOpenGL1.1?including GLU; - DaoSDL: binding to Single DirectMedia Layer, partially finished; - DaoCamellia: binding to camellia image processing library; The previous modules DaoMySQL, DaoBLAS and DaoPython are not yet upgraded accordingly for this release. Have fun! Limin Fu phoolimin[AT]gmail[DOT]com From spe.stani.be at gmail.com Wed Nov 29 18:15:45 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 29 Nov 2006 15:15:45 -0800 Subject: SPE refuses. In-Reply-To: References: <1164828687.755193.4900@l39g2000cwd.googlegroups.com> Message-ID: <1164842145.465496.135210@h54g2000cwb.googlegroups.com> Do you have python-wxversion installed? $sudo apt-get install python-wxversion Stani On 29 nov, 23:21, egbert wrote: > On Wed, Nov 29, 2006 at 11:31:27AM -0800, SPE - Stani's Python Editor wrote:> If wxPython is rightly installed, which means that "import wx" works > > fine and "wx.VERSION" gives the right version, you can ignore the > > wxPython warning.In a Python shell the commands 'import wx' and 'wx.VERSION' give: > (2,6,3,2,'') > > > Please cd do your site-packages directory and do "python SPE.py > > --debug" and see the error message.In gnome-terminal /usr/lib/python2.4/site-packages/_spe > the command: 'python SPE.py --debug' produces the same error: > You need to install at least wxPython v2.5.4.1 to run SPE. > Get it fromhttp://www.python.org > > Well, I got it from the debian repositories. > > e. > -- > Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 > ======================================================================== From fredrik at pythonware.com Sat Nov 25 09:32:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 25 Nov 2006 15:32:18 +0100 Subject: Importing module of data dicts and constants In-Reply-To: <676224240611250619s764cb644kb254536e3f7aca2e@mail.gmail.com> References: <676224240611250619s764cb644kb254536e3f7aca2e@mail.gmail.com> Message-ID: Nathan Harmston wrote: > I ve got a single module which I m using to contain a lot of > dictionaries, constants, general information, which are used by > various other modules. However I can't seem to access them: > > in data.py > _SEQTYPE_DNA = 0 > _SEQTYPE_RNA = 1 > _SEQTYPE_PROT = 2 > _seqType = { "DNA":_SEQTYPE_DNA, "RNA":_SEQTYPE_RNA, "PROTEIN":_SEQTYPE_PROT } why do they all start with an underscore? > but in test.py > from data import * as clearly stated in the documentation, "from import *" consider names that start with an underscore to be private. also see: http://effbot.org/pyref/reserved-identifier-classes.htm > I think I m doing something incredibly wrong/stupid here.... well, you're only supposed to be using "from import *" if you know what you're doing, so if you need to ask, you've obviously broken the rules ;-) From john106henry at hotmail.com Thu Nov 30 15:17:50 2006 From: john106henry at hotmail.com (John Henry) Date: 30 Nov 2006 12:17:50 -0800 Subject: Is there an easier way to express this list slicing? In-Reply-To: References: <1164913125.509492.54060@79g2000cws.googlegroups.com> Message-ID: <1164917869.978435.63370@f1g2000cwa.googlegroups.com> Thomas Ploch wrote: > > I had a little bit of fun while writing this: > > itemList = (a,b,c1,c2,c3,d1,d2,d3,d4,d5) and > itemList2 = (a1,a2,a3,b,c,d1,d2,d3,d4,d5) the next time. > Huh? What's a,b,....d5? > def getSlices(aCount, bCount, cCount, dCount, items): > a,b,c,d = (items[0:aCount], > items[aCount:aCount+bCount], > items[aCount+bCount:aCount+bCount+cCount], > item[aCount+bCount+cCount:aCount+bCount+cCount+dCount]) You meant "items" here, right? > return list(a),list(b),list(c),list(d) > > >>>a,b,c,d = getSlices(1,1,3,5,itemList) > >>>print a,b,c,d > ['a'] ['b'] ['c1', 'c2', 'c3'] ['d1', 'd2', 'd3', 'd4', 'd5'] > > >>>a,b,c,d = getSlices(3,1,1,0,itemList2) > >>>print a,b,c,d > ['a1', 'a2', 'a3'] ['b'] ['c'] [] > > %-) > > Thomas From fredrik at pythonware.com Wed Nov 15 11:36:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Nov 2006 17:36:48 +0100 Subject: Python-2.5.exe? In-Reply-To: References: Message-ID: Andrew Burton wrote: > What Python is best for installing to a USB Drive? I've actually got > 2.5 on a drive, but I forget which installation package I used. It > seems to me that it was an EXE file, but I cannot seem to find one of > those today. > > Can the Python-2.5.msi installation files from python.org be installed > so as not to touch the registry, to make them portable? python doesn't depend on the registry settings for normal use, so you can simply install python as usual, copy python25.dll from c:\windows\system32 to c:\python25, and then copy (or move) the entire c:\python25 tree to your USB drive. From bearophileHUGS at lycos.com Thu Nov 2 12:47:18 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Nov 2006 09:47:18 -0800 Subject: Python in sci/tech applications In-Reply-To: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> References: <1162479244.031672.209580@e3g2000cwe.googlegroups.com> Message-ID: <1162489638.013433.102180@h48g2000cwc.googlegroups.com> mattf: > 3) -There's a problem with development under Windows. It's possibile to compile Python with MinGW, and to create extensions with it. So some site can host a single zip file that contains both MinGW and Python compiled with it, all ready and set. A person not much expert can then create compiled small extensions in a short time without too much complexities. (Or maybe the D language can be packed into that, instead of MinGW, to do similar things. D can be a good language used with Python) But then probably PIL, scipy, etc have to be compiled again for such alternative official or semi-official Python distribution. Bye, bearophile From no-spam at no-spam-no-spam.invalid Sun Nov 12 11:25:00 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sun, 12 Nov 2006 17:25:00 +0100 Subject: numpy/scipy: correlation In-Reply-To: References: Message-ID: robert wrote: > Robert Kern wrote: > http://links.jstor.org/sici?sici=0162-1459(192906)24%3A166%3C170%3AFFPEOC%3E2.0.CO%3B2-Y > > tells: > probable error of r = 0.6745*(1-r**2)/sqrt(N) > > A simple function of r and N - quite what I expected above roughly for > the N-only dep.. But thus it is not sensitive to above considerations > about 'boring' data. With above example it would spit a decrease of this > probable coef-err from > 0.0115628571429 to 0.00548453410954 ! This 1929 formula for estimating the error of correlation coefficient seems to make some sense for r=0 . I do monte carlo on correlating random series: >>> X=numpy.random.random(10000) >>> l=[] >>> for i in range(200): ... Z=numpy.random.random(10000) ... l.append( sd.correlation((X,Z))[2] ) #collect coef's ... >>> mean(l) 0.000327657082234 >>> std(l) 0.0109120766158 # thats how the coef jitters >>> std(l)/sqrt(len(l)) 0.000771600337185 >>> len(l) 200 # now # 0.6745*(1-r**2)/sqrt(N) = 0.0067440015079 # vs M.C. 0.0109120766158 ? 0.000771600337185 but the fancy factor of 0.6745 is significantly just fancy for r=0. then for a higher (0.5) correlation: >>> l=[] >>> for i in range(200): ... Z=numpy.random.random(10000)+array(range(10000))/10000.0 ... l.append( sd.correlation((X+array(range(10000))/10000.0,Z))[2] ) ... >>> mean(l) 0.498905642552 >>> std(l) 0.00546979583163 >>> std(l)/sqrt(len(l)) 0.000386772972425 #now: # 0.6745*(1-r**2)/sqrt(N) = 0.00512173224849) # vs M.C. 0.00546979583163 ? 0.000386772972425 => there the 0.6745 factor and (1-r**2) seem to get the main effect ! There is something in it. -- Now adding boring data: >>> boring=ones(10001)*0.5 >>> X=numpy.random.random(10000) >>> l=[] >>> for i in range(200): ... Z=concatenate((numpy.random.random(10000)+array(range(10000))/10000.0,boring)) ... l.append( sd.correlation((concatenate((X+array(range(10000))/10000.0,boring)),Z))[2] ) ... >>> mean(l) 0.712753628489 # r >>> std(l) 0.00316163649888 # r_err >>> std(l)/sqrt(len(l)) 0.0002235614608 # now: # 0.6745*(1-r**2)/sqrt(N) = 0.00234459971461 #N=20000 # vs M.C. streuung 0.00316163649888 ? 0.0002235614608 => the boring data has an effect on coef-err which is significantly not reflected by the formula 0.6745*(1-r**2)/sqrt(N) => I'll use this formula to get a downside error estimate for the correlation coefficient: ------------------------------------------ | r_err_down ~= 1.0 * (1-r**2)/sqrt(N) | ------------------------------------------ (until I find a better one respecting the actual distribution of data) Would be interesting what MATLAB & Octave say ... -robert From bj_666 at gmx.net Sat Nov 18 16:07:00 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 18 Nov 2006 22:07:00 +0100 Subject: print with variable justification (with *) References: <1163883589.401180.271190@m73g2000cwd.googlegroups.com> Message-ID: In <1163883589.401180.271190 at m73g2000cwd.googlegroups.com>, Why Tea wrote: > print format % values > An optional minimum width of the conversion, specified using one or > more digits or an asterisk (*), which means that the width is taken > from the next item in values > > That's from one of O'reilly's books. But there is no example and I > couldn't get it to work by trials and errors. Does anyone have a > working example? In [50]: '%*s' % (5, 'spam') Out[50]: ' spam' In [51]: '%*s' % (10, 'spam') Out[51]: ' spam' In [52]: '%*s' % (15, 'spam') Out[52]: ' spam' Ciao, Marc 'BlackJack' Rintsch From will at willNOmcguganSPAM.com Wed Nov 29 17:29:09 2006 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Wed, 29 Nov 2006 22:29:09 +0000 Subject: Remarkable results with psyco and sieve of Eratosthenes In-Reply-To: <1164837289.295731.178070@h54g2000cwb.googlegroups.com> References: <1164837289.295731.178070@h54g2000cwb.googlegroups.com> Message-ID: <456e09b7$0$1505$db0fefd9@news.zen.co.uk> Steve Bergman wrote: > Just wanted to report a delightful little surprise while experimenting > with psyco. > The program below performs astonoshingly well with psyco. > > It finds all the prime numbers < 10,000,000 Actualy, it doesn't. You forgot 1 and 2. Will McGugan -- blog: http://www.willmcgugan.com From richie at entrian.com Thu Nov 30 06:23:40 2006 From: richie at entrian.com (Richie Hindle) Date: Thu, 30 Nov 2006 11:23:40 +0000 Subject: why would anyone use python when java is there? In-Reply-To: <1164818505.696250.264070@h54g2000cwb.googlegroups.com> References: <1164762232.220759.57160@h54g2000cwb.googlegroups.com> <1164764454.043697.125730@j72g2000cwa.googlegroups.com> <1164818505.696250.264070@h54g2000cwb.googlegroups.com> Message-ID: [Adam] > For the life of me I can't understand why he would troll > comp.lang.python when comp.lang.lisp is there. +1 QOTW! -- Richie Hindle richie at entrian.com From sjmachin at lexicon.net Sun Nov 26 06:46:06 2006 From: sjmachin at lexicon.net (John Machin) Date: 26 Nov 2006 03:46:06 -0800 Subject: a -very- case sensitive search In-Reply-To: References: <1164490795.866046.133230@45g2000cws.googlegroups.com> Message-ID: <1164541566.246893.279680@l12g2000cwl.googlegroups.com> Paul McGuire wrote: > "Ola K" wrote in message > news:1164490795.866046.133230 at 45g2000cws.googlegroups.com... > > Hi, > > I am pretty new to Python and I want to make a script that will search > > for the following options: > > 1) words made of uppercase characters -only- (like "YES") > > 2) words made of lowercase character -only- (like "yes") > > 3) and words with only the first letter capitalized (like "Yes") > > * and I need to do all these considering the fact that not all letters > > are indeed English letters. > > > > I went through different documention section but couldn't find a right > > condition, function or method for it. > > Suggestions will be very much appriciated... > > --Ola > > > Ola, > > You may be new to Python, but are you new to regular expressions too? I am > no wiz at them, but here is a script that takes a stab at what you are > trying to do. (For more regular expression info, see > http://www.amk.ca/python/howto/regex/.) > > The script has these steps: > - create strings containing all unicode chars that are considered "lower" > and "upper", using the unicode.is* methods > - use these strings to construct 3 regular expressions (or "re"s), one for > words of all lowercase letters, one for words of all uppercase letters, and > one for words that start with an uppercase letter followed by at least one > lowercase letter. > - use each re to search the string u"YES yes Yes", and print the found > matches > > I've used unicode strings throughout, so this should be applicable to your > text consisting of letters beyond the basic Latin set (since Outlook Express > is trying to install Israeli fonts when reading your post, I assume these > are the characters you are trying to handle). I'd guessed the OP was in Israel from his e-mail address. If that's what Outlook Express is doing, then that's conclusive proof :-) An aside to the OP: Pardon my ignorance, but does Hebrew have upper and lower case? > You may have to do some setup > of your locale for proper handling of unicode.isupper, etc., Whatever gave you that impression? > but I hope this > gives you a jump start on your problem. > > -- Paul > > > import sys > import re > > uppers = u"".join( unichr(i) for i in range(sys.maxunicode) > if unichr(i).isupper() ) > lowers = u"".join( unichr(i) for i in range(sys.maxunicode) > if unichr(i).islower() ) Just in case the OP is running a 32-bit unicode implementation, you might want to make that xrange, not range :-) > > allUpperRe = ur"\b[%s]+\b" % uppers > allLowerRe = ur"\b[%s]+\b" % lowers > capWordRe = ur"\b[%s][%s]+\b" % (uppers,lowers) > > regexes = [ > (allUpperRe, "all upper"), > (allLowerRe, "all lower"), > (capWordRe, "title case"), > ] > for reString,label in regexes: > reg = re.compile(reString) > result = reg.findall(u" YES yes Yes ") > print label,":",result > > Prints: > all upper : [u'YES'] > all lower : [u'yes'] > title case : [u'Yes'] Cheers, John From martin at v.loewis.de Thu Nov 16 18:31:06 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Nov 2006 00:31:06 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: References: <455CED78.1060604@v.loewis.de> Message-ID: <455CF4BA.1050608@v.loewis.de> gabor schrieb: >> All this code will typically work just fine with the current behavior, >> so people typically don't see any problem. >> > > i am sorry, but it will not work. actually this is exactly what i did, > and it did not work. it dies in the os.path.join call, where file_name > is converted into unicode. and python uses 'ascii' as the charset in > such cases. but, because listdir already failed to decode the file_name > with the filesystem-encoding, it usually also fails when tried with > 'ascii'. Ah, right. So yes, it will typically fail immediately - just as you wanted it to do, anyway; the advantage with this failure is that you can also find out what specific file name is causing the problem (whereas when listdir failed completely, you could not easily find out the cause of the failure). How would you propose listdir should behave? Regards, Martin From wojciech_mula at poczta.null.onet.pl.invalid Tue Nov 14 10:08:53 2006 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Tue, 14 Nov 2006 15:08:53 +0000 (UTC) Subject: Tkinter: Strange behavior using place() and changing cursors References: <1163467464.043668.44630@e3g2000cwe.googlegroups.com> Message-ID: Mudcat wrote: > [...] You have to set cursor once, Tk change it automatically: > def buildFrame(self): > self.f = Frame(self.master, height=32, width=32, relief=RIDGE, > borderwidth=2) > self.f.place(relx=.5,rely=.5) #self.f.bind( '', self.enterFrame ) #self.f.bind( '', self.leaveFrame ) self.f.configure(cursor = 'sb_h_double_arrow') From bblais at bryant.edu Fri Nov 3 11:24:05 2006 From: bblais at bryant.edu (Brian Blais) Date: Fri, 03 Nov 2006 11:24:05 -0500 Subject: setting up wxPython on a Mac Message-ID: <454B6D25.9030002@bryant.edu> Hello, I have a wxPython program that I would like to give to a friend of mine who has a Mac. Is there a resource out there that can tell me what steps I need to follow to do this? Under windows, I would just install Enthought, and it would work without any modifications. I don't know Macs all that well, but is there something similar? Thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From gslindstrom at gmail.com Thu Nov 23 13:14:58 2006 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Thu, 23 Nov 2006 12:14:58 -0600 Subject: Python business software? Message-ID: Hello- My wife runs a sewing/embroidery business and has asked me to write a system to help her with her client database, inventory, and accounts receivable/payable. I've looked into using either PythonCard or Dabo (I like both packages) but thought I ask the list if there is anything like this out there already. Tasks such as tracking clients are fairly routine in business, so maybe there's something close that I could hack in order to add details specific to our business. We only have one computer right now, so we don't *need* a web-based system but we plan on growing so it would be an option. Thanks for you help, --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Thu Nov 30 13:50:50 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 30 Nov 2006 12:50:50 -0600 Subject: extremely slow array indexing? In-Reply-To: <1164911616.009985.210320@h54g2000cwb.googlegroups.com> References: <1164907021.765969.129280@80g2000cwy.googlegroups.com> <1164908923.363433.43770@l39g2000cwd.googlegroups.com> <1164911616.009985.210320@h54g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Hi Grace, > What Will McGugan said, plus: > 1. Post *much* more of your code e.g. all relevant parts :-) Note that Grace has also posted this to numpy-discussion and with prompting provided the following snippet as a distillation of the key slow part: from numpy import * componentcount = 300000 currSum = zeros(componentcount) row = zeros(componentcount) #current row rowcount = 50000 for i in range(1,rowcount): row[:] = 1 currSum = currSum + row; As it is, the OP gets through 1000 rows every 7 seconds or so on their machine, and I get about the same on mine. Changing the last line to "currSum += row" gets a 3x speedup. Dropping the "row[:] = 1" line as it's a really just a time-consuming no-op in the example and probably not an accurate reflection of what's going on in the real code gets you another 2x speedup. -- 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 rw at smsnet.pl Tue Nov 28 09:48:14 2006 From: rw at smsnet.pl (Rob Wolfe) Date: 28 Nov 2006 06:48:14 -0800 Subject: Question about import and sys.path In-Reply-To: <1164700262.370760.129210@l12g2000cwl.googlegroups.com> References: <1164700262.370760.129210@l12g2000cwl.googlegroups.com> Message-ID: <1164725294.490337.224430@l12g2000cwl.googlegroups.com> Frank Millman wrote: > Hi all > > I am writing a business/accounting application. Once a user has logged > in they are presented with a menu. Each menu option has a description > and an associated file name and program name. The file name is the name > of a .py file (impName) and the program name is the name of a class in > that file which I instantiate to run the program (progName). > > When a menu option is selected, I execute the program like this - > imp = __import__(impName) > app = getattr(imp,progName)() > > All the .py files are stored in one directory, which I add to sys.path > at the beginning of the session. It all seems to work fine. > > Now my program directory is getting cluttered, so I want to split it > into sub-directories, one per company (it is a multi-company system). I > can do that, and each of the subdirectories can be added to sys.path, > so it should work as at present. > > However, I want the ability to have duplicate program names stored in > different subdirectories. At the time of selecting the menu option I > know which company is active, so I know which directory I want to run > the program from, but there does not seem to be a way to tell 'import' > to import from a particular directory. I suggest to use module `imp`. For example: I assume paths like this: app/ importer.py company1/ prog1.py the module in the company1 subdirectory: # prog1 class SomeClass(object): def test(self): return "%s: %s" % (__file__, self.__class__.__name__) and the module with your menu could look like this: # importer.py def get_class(classname, impname, company): fp, pathname, description = imp.find_module(impname, [company]) m = imp.load_module(impname, fp, pathname, description) return getattr(m, classname) obj = get_class("SomeClass", "prog1", "company1")() print obj.test() -- HTH, Rob From flynnguy at gmail.com Fri Nov 24 11:07:30 2006 From: flynnguy at gmail.com (flynnguy at gmail.com) Date: 24 Nov 2006 08:07:30 -0800 Subject: pexpect problems Message-ID: <1164384450.074731.267330@45g2000cws.googlegroups.com> I am trying to essentially fork a rsync process from my python script and I am having some issues with the forking part. My program basically checks to see if I need to transfer a file and if it does, it calls the transferItem() function below: def transferItem(filelist): hostname, passwd, transdir, filepath = filelist command = "nice -n +19 %s --partial --bwlimit=\"%d\" \"%s\" %s:%s" % (COMMAND_TO_CHECK, BANDWIDTH_LIMIT, filepath, hostname, transdir) p = pexpect.spawn(command) try: ret = p.expect(["(yes/no)", "Password:"]) if ret == 0: p.sendline("yes") p.expect("Password:") p.sendline(passwd) p.expect(pexpect.EOF, timeout=999) except: print 'problem transferring file' Now this seems to partially work (it transfers the file) but I have a few issues I'm hoping someone can help me with. First there is the timeout issue. Without the timeout=999 parameter, the default timeout is 30 seconds. I'd rather not have any timeout because the files I need to transfer can be quite large and may take several days in some cases. I tried p.close(wait=False) but that creates a defunct process and doesn't seem to transfer any of the file. I can also say p.interact() which won't timeout on me but it also doesn't fork into the background. I thought the best solution would be to use the p.interact() and fork the process but I can't seem to get that working. Anyone have any ideas or suggestions that might help me? Also just as a background in case it helps, I am currently writing a pickled object (List of list) to a file using a web frontend (using django) and then I have a monitor script which first checks if it should transfer a file (based on how many transfers are currently running) and then opens the pickled object and pop's off the first item and sends that as input to the above function which I'm hoping will start the rsync and then keep on chugging. I'd really appreciate any help anyone could offer. -Chris From michael at doubleserver.com Fri Nov 24 19:33:47 2006 From: michael at doubleserver.com (J. Michael Caine) Date: Fri, 24 Nov 2006 16:33:47 -0800 Subject: namespace curiosity Message-ID: <200611241633.48043.michael@doubleserver.com> I just noticed something that may well have an obvious explanation (apologies in advance if so). Little demo illustrates: >>> def x(y = {1:1}): ... y[1] = y[1] + 1 ... print y[1] ... >>> x() 2 >>> x() 3 and so on; y continues to be updated rather than reset each call to x(). dir() suggests that y did _not_ somehow get into the global namespace, nor do I see anything else that explains the behavior obviously. This only occurs with dicts (or rather, possibly with any object that is merely updated within x(), rather than reassigned within x()... I haven't tested). I've been pythoning for a little while now, but haven't participated in this usenet; you're welcome to consider me a newbie and be gentle with any explanation of my oversight or whatever. The nature of this problem made it difficult for me to investigate - to see if anyone else has reported or explained it. TIA. From daigno at gmail.com Tue Nov 21 15:19:11 2006 From: daigno at gmail.com (=?ISO-8859-1?Q?=C9ric_Daigneault?=) Date: Tue, 21 Nov 2006 15:19:11 -0500 Subject: Reference class in class creation Message-ID: <45635F3F.5090701@gmail.com> oops... Change : class SomeContainer(object): a = SomeElement(self) for class SomeContainer(object): pass container = SomeContainer() element = SomeElement(container) would certainly make more sense... Eric :D. From python at contrado.com.au Wed Nov 29 05:23:54 2006 From: python at contrado.com.au (Graeme Matthew) Date: Wed, 29 Nov 2006 21:23:54 +1100 Subject: Asyncore Medusa Example Message-ID: <456D5FBA.2010909@contrado.com.au> Hi all does anyone know where you can find examples of how to write a native python webserver, I have looked at medusa and asyncore but there are no real examples and the doco is very light any help is appreciated regards graeme From __peter__ at web.de Tue Nov 14 06:07:51 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Nov 2006 12:07:51 +0100 Subject: Seeking assistance - string processing. References: <1163500326.492067.234080@k70g2000cwa.googlegroups.com> <1163501742.957889.57410@m73g2000cwd.googlegroups.com> Message-ID: billpaterson2006 at googlemail.com wrote: > Thanks so much, a really elegant solution indeed. > > I have another question actually which I'm praying you can help me > with: > > with regards to the .jpg conversion to .jpg]] and .gif -> .gif]] > > this works, but only when .jpg/.gif is on it's own line. > > i.e: > > .jpg > > will get converted to: > > .jpg]] > > but > > Image:test.jpg > > gets converted to: > > [[Image:test.jpg > > rather than > > [[Image:test.jpg]] > > ------------------ > > Hope you can help again! Cheers It does not do the right thing in all cases, but maybe you can get away with for line in lines: if line.startswith("==="): line = line.rstrip() + "===\n" line = line.replace("--------------------","----") line = line.replace("img:","[[Image:") line = line.replace(".jpg",".jpg]]") line = line.replace(".gif",".gif]]") output_lines.append(line) Peter From bearophileHUGS at lycos.com Wed Nov 22 13:02:20 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Nov 2006 10:02:20 -0800 Subject: text file parsing (awk -> python) In-Reply-To: References: Message-ID: <1164218540.617987.72130@b28g2000cwb.googlegroups.com> Peter Otten, your solution is very nice, it uses groupby splitting on empty lines, so it doesn't need to read the whole files into memory. But Daniel Nogradi says: > But the names of the fields (node, x, y) keeps changing from file to > file, even their number is not fixed, sometimes it is (node, x, y, z). Your version with the converters dict fails to convert the number of node, z fields, etc. (generally using such converters dict is an elegant solution, it allows to define string, float, etc fields): > converters = dict( > x=int, > y=int > ) I have created a version with a RE, but it's probably too much rigid, it doesn't handle files with the z field, etc: data = """node 10 y 1 x -1 node 11 x -2 y 1 z 5 node 12 x -3 y 1 z 6""" import re unpack = re.compile(r"(\D+) \s+ ([-+]? \d+) \s+" * 3, re.VERBOSE) result = [] for obj in unpack.finditer(data): block = obj.groups() d = dict((block[i], int(block[i+1])) for i in xrange(0, 6, 2)) result.append(d) print result So I have just modified and simplified your quite nice solution (I have removed the pprint, but it's the same): def open(filename): from cStringIO import StringIO return StringIO(data) from itertools import groupby records = [] for empty, record in groupby(open("records.txt"), key=str.isspace): if not empty: pairs = ([k, int(v)] for k,v in map(str.split, record)) records.append(dict(pairs)) print records Bye, bearophile From steve at REMOVE.THIS.cybersource.com.au Sun Nov 19 08:49:29 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 20 Nov 2006 00:49:29 +1100 Subject: tempfile.NamedTemporaryFile wont work References: <456049ca$0$4692$426a74cc@news.free.fr> Message-ID: On Sun, 19 Nov 2006 13:11:13 +0100, Imbaud Pierre wrote: > On suse 9.3, tempfile.NamedTemporaryFile() doesnt work as expected. [snip] > Symptom: the file does not always exist, after the call to > NamedTemporaryFile(). Or at least its not seen by the strings command, > or by os.path.exists. > > I guess the bug is pretty much os dependent, or even filesystem > dependent (Im on reiserfs). Maybe the os is buggy, maybe, somehow, the > python interface. Or did I miss something? > Shame, I didnt even try to check for a python bug tracker. I can verify this problem occurs on Fedora Core 5 too: import os import sys import tempfile import subprocess def test(n): chunk = ': +++ abcd +++' for i in xrange(n): tf = tempfile.NamedTemporaryFile() tfName = tf.name tf.seek(0) tf.write(str(i) + chunk) tf.flush() if not os.path.exists(tfName): print 'pre-check: %s not there' % tfName subprocess.Popen(['strings', tfName]) if not os.path.exists(tfName): print 'post-check: %s not there' % tfName And here is a typical run, with the boring bits removed for ease of reading: >>> test(30) 0: +++ abcd +++ 1: +++ abcd +++ [ more of the same ] 14: +++ abcd +++ strings: '/tmp/tmpOALbx9': No such file 16: +++ abcd +++ 17: +++ abcd +++ 18: +++ abcd +++ [ more of the same ] 27: +++ abcd +++ strings: /tmp/tmpdc52Nz: No such file or directory 29: +++ abcd +++ Curiouser and curiouser... not only does os.path.exist always report the temp file as existing (at least in my tests), even when strings can't find it, but strings returns different error messages. Is it possible this is a bug in strings? -- Steven. From ak at silmarill.org Tue Nov 21 00:17:41 2006 From: ak at silmarill.org (Rainy) Date: 20 Nov 2006 21:17:41 -0800 Subject: Vim scripts for editing Python? Message-ID: <1164086261.774376.125490@j44g2000cwa.googlegroups.com> Hi, did anyone make a good set of scripts for editing Python in Vim? I know there is one on vim.org but it isn't very advanced. thx.. From steve at REMOVEME.cybersource.com.au Thu Nov 16 03:45:18 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 16 Nov 2006 19:45:18 +1100 Subject: Secure Python References: <455c1665@quokka.wn.com.au> Message-ID: On Thu, 16 Nov 2006 17:44:37 +1000, timmy wrote: > congraulations you have discovered loops and their misuse Did you have a point in your utterly inane comment, or did you just want to see your name on Usenet? In any case, it isn't just "loops" that are dangerous. print 2**512**512 No loop there, but it will operate as a lovely DoS attack if you run it. The Original Poster is suggesting running UNTRUSTED code. That means you have to assume that it will be actively hostile, but even if it isn't deliberately hostile, there will be bugs which the developer can't control. He wants to run this untrusted (hostile or buggy or both) code in an environment where it can't do bad things. "Bad things" include Denial of Service attacks. So, Timmy, let's hear your brilliant scheme for preventing DoS attacks when running hostile code in Python. -- Steven D'Aprano From gheorghe.postelnicu at gmail.com Mon Nov 27 15:17:08 2006 From: gheorghe.postelnicu at gmail.com (Gheorghe Postelnicu) Date: Mon, 27 Nov 2006 15:17:08 -0500 Subject: Several entries on Tile and TableList at the Tkinter wiki Message-ID: <8094b1b60611271217i6ef19cb0reb26ab7478e96e46@mail.gmail.com> Hi, Thanks for pointing out this resource. I have indeed used Tkinter in a couple of applications, but I knew nothing about this wiki. This is very helpful. Thanks, -- Gheorghe Postelnicu, PhD MGH, Harvard Medical School From steve at REMOVE.THIS.cybersource.com.au Sat Nov 11 09:04:33 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 12 Nov 2006 01:04:33 +1100 Subject: handling many default values References: Message-ID: On Fri, 10 Nov 2006 17:11:24 +0000, Alan G Isaac wrote: > My class MyClass reuses many default parameters > with a small number of changes in each instance. Let me see that I understand. Are you doing something like this? # Class takes a lot of arguments a = MyClass(0, 1, 2, 3, 4, 5, ..., 99) # and instances vary only by one or two of those args b = MyClass(0, 2, 2, 3, 4, 5, ..., 99) c = MyClass(0, 3, 2, 3, 4, 5, ..., 99) d = MyClass(0, 4, 2, 3, 4, 5, ..., 99) e = MyClass(0, 5, 2, 3, 4, 5, ..., 99) ... z = MyClass(0, 26, 2, 3, 4, 5, ..., 99) If that's the case, I'd seriously rethink your class design. It is hard to advise a better design without knowing more about the class, but I'd be surprised if you can't use subclassing to reduce the number of parameters needed. E.g.: class MyClass(object): def __init__(self, arg0): self.arg0 = arg0 # now fill in arguments 1 through 99 with sensible values class MyClass2(MyClass): def __init__(self, arg1): """Just like MyClass, but arg0 has a fixed value and arg1 varies""" super(MyClass, self).__init__("fixed value") self.arg1 = arg1 and so on for as many subclasses that you need. In the same way, perhaps you can group those arguments. E.g. instead of this: class WordProcessingDoc(object): def __init__(self, page_width, page_height, left_margin, right_margin, top_margin, bottom_margin, font_face, font_size, font_style, line_size, justification): # and many more # and many, many more arguments pass Create some classes, and pass instances of them to the main class: class CharStyle(object): def __init__(self, font_face, font_size, font_style): pass class PageStyle(object): def __init__(self, width, height, left, right, top, bottom): pass class WordProcessingDoc(object): def __init__(self, pagestyle, charstyle, paragraphstyle): pass > For various reasons I decided to put all the > parameters in a separate Params class, instances > of which reset the default values based on keyword > arguments, like this: > > class Params: > def __init__(self,**kwargs): > #set lots of default values > ... > #set the deviations from defaults > self.__dict__.update(kwargs) > > Is this a reasonable approach overall? > (Including the last line.) (1) If there really is no alternative to a class with many arguments; (2) and instances can vary those arguments unpredictably; then this approach seems reasonable to me. But I really suggest you rethink your class design. -- Steven. From bedouglas at earthlink.net Wed Nov 15 20:11:51 2006 From: bedouglas at earthlink.net (bruce) Date: Wed, 15 Nov 2006 17:11:51 -0800 Subject: Python v PHP: fair comparison? In-Reply-To: <455bad51$0$26230$426a74cc@news.free.fr> Message-ID: <1a6e01c7091c$34212470$0301a8c0@tmesa.com> interesting ongoing thread... i've seen a number of these over the years.. my language is better than your language!! i'm sure this question on the php list would have findings/results that are essentially opposite of what is being discussed here! -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Bruno Desthuilliers Sent: Wednesday, November 15, 2006 4:35 PM To: python-list at python.org Subject: Re: Python v PHP: fair comparison? walterbyrd a ?crit : > Michael Torrie wrote: > > >>Absolutely false. Most of my standalone, command-line scripts for >>manipulating my unix users in LDAP are written in PHP, although we're >>rewriting them in python. >> > > > I would say that you are one of very few who use PHP for sys-admin > tasks - and even you have switched to Python. In general, it does not > seem to me that PHP has caught on as a sys-admin language. > > However, as sys-admin scripting langanges go, I would also say that > Python is far less popular than butt-ugly Perl. Again - just based on > what I've seen. Perl is a scripting language. By 'design'. It's meant to be a better sh+sed+awk. Python is a general purpose programming language meant to fill the gap between shell scripts and C programs. So Perl is obviously a better scripting language than Python. The problem is that Q&D sys-admin scripts tend to become full-blown apps - and then, Perl starts to suck. -- http://mail.python.org/mailman/listinfo/python-list From sturlamolden at yahoo.no Thu Nov 16 16:09:03 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 16 Nov 2006 13:09:03 -0800 Subject: About alternatives to Matlab In-Reply-To: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> References: <1161613941.550194.204870@e3g2000cwe.googlegroups.com> Message-ID: <1163711343.870829.110030@h48g2000cwc.googlegroups.com> Boris wrote: > Hi, is there any alternative software for Matlab? Although Matlab is > powerful & popular among mathematical & engineering guys, it still > costs too much & not publicly open. So I wonder if there's similar > software/lang that is open & with comparable functionality, at least > for numerical aspect. Thanks! I have used Matlab for years, and has recently changed to Python. In addition one needs NumPy and Matplotlib, and perhaps SciPy. Other useful packages are PyGTK for GUI, PyGame for multimedia, PyOpenGL for 3D graphics, Mpi4Py for parallel computation, etc. You will find python packages for nearly any conceivable task. Unlike Matlab, Python is a general purpose programming language, and a distant cousin of Lisp. The Python language is fare more expressive and productive than Matlab, yet even more easy to use. The NumPy package is the core requirement for numerical work in Python. It is quite different form Matlab, but I think it is more powerful. Particularly, arrays are passed by reference (not by value), and indexing creates view matrices. To compare Matlab with NumPy we can e.g. use the D4 discrete wavelet transform. I have here coded it in Matlab and Python/NumPy using Tim Swelden's lifting scheme. First the Matlab version (D4_Transform.m): function x = D4_Transform(x) % D4 Wavelet transform in Matlab % (C) Sturla Molden C1 = 1.7320508075688772; C2 = 0.4330127018922193; C3 = -0.066987298107780702; C4 = 0.51763809020504137; C5 = 1.9318516525781364; s1 = zeros(ceil(size(x)/2)); d1 = zeros(ceil(size(x)/2)); d2 = zeros(ceil(size(x)/2)); odd = x(2:2:end); even = x(1:2:end-1); d1(:) = odd - C2*even; s1(1) = even(1) + C2*d1(1) + C3*d1(end); s1(2:end) = even(2:end) + C2*d1(2:end) + C3*d1(1:end-1); d2(1) = d1(1) + s1(end); d2(2:end) = d1(2:end) + s1(1:end-1); x(1:2:end-1) = C4*s1; x(2:2:end) = C5*d2; if (length(x) >2) x(1:2:end-1) = D4_Transform(x(1:2:end-1)); end Then the Python version (D4.py): import numpy import time def D4_Transform(x, s1=None, d1=None, d2=None): """ D4 Wavelet transform in NumPy (C) Sturla Molden """ C1 = 1.7320508075688772 C2 = 0.4330127018922193 C3 = -0.066987298107780702 C4 = 0.51763809020504137 C5 = 1.9318516525781364 if d1 == None: d1 = numpy.zeros(x.size/2) s1 = numpy.zeros(x.size/2) d2 = numpy.zeros(x.size/2) odd = x[1::2] even = x[:-1:2] d1[:] = odd[:] - C1*even[:] s1[0] = even[0] + C2*d1[0] + C3*d1[-1] s1[1:] = even[1:] + C2*d1[1:] + C3*d1[:-1] d2[0] = d1[0] + s1[-1] d2[1:] = d1[1:] + s1[:-1] even[:] = C4 * s1[:] odd[:] = C5 * d2[:] if x.size > 2: D4_Transform(even,s1[0:even.size/2],d1[0:even.size/2],d2[0:even.size/2]) if __name__ == "__main__": x = numpy.random.rand(2**23) t0 = time.clock() D4_Transform(x) t = time.clock() print "Elapsed time is %.6f seconds" % (t-t0) Now let's do benchmark on my laptop (1.73 GHz Pentium M, 0.99 GB RAM). I have stopped paying for Matlab maintenance (for reasons that will be obvious), so I only have R14 Service Pack 2 for comparison. First we try Matlab (R14 Service Pack 2): >> x = rand(2^23,1); >> tic; D4_Transform(x); toc Elapsed time is 27.145438 seconds. Then we Python 2.4.4 with NumPy 1.0: C:\develop\python\D4>python D4.py Elapsed time is 3.364887 seconds That is quite astonishing. If anyone wonders why I think Travis Oliphant and the NumPy team should be knighted, then this is the answer. The Mathworks' product only achieved 100% * 3/27 = 11% the speed of Python/NumPy, and is infinitely more expensive. Does anyone wonder why I am not paying for Matlab maintenance anymore? Sorry Mathworks, I have used your product for years, but you cannot compete with NumPy. Cheers, Sturla Molden From george.sakkis at gmail.com Sat Nov 18 17:27:03 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 18 Nov 2006 14:27:03 -0800 Subject: Overwrite only one function with property() References: Message-ID: <1163888823.172705.109520@h54g2000cwb.googlegroups.com> Kai Kuehne wrote: > Hi list! > It is possible to overwrite only one function with the property-function? > > x = property(getx, setx, delx, 'doc') > > I just want to overwrite setx, but when I set the others to None, > I can't read and del the member. Any ideas or is this not possible? There are no default functions for getx, setx, delx; you have to specify what you expect to happen when you write a.p, a.p = v and del a.p, respectively. What would, for example, be the default getx that you don't want to overwrite ? George From Thomas.Ploch at gmx.net Thu Nov 30 17:35:36 2006 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Thu, 30 Nov 2006 23:35:36 +0100 Subject: best way to align words? In-Reply-To: <1164925391.696612.64860@80g2000cwy.googlegroups.com> References: <1164925391.696612.64860@80g2000cwy.googlegroups.com> Message-ID: <456F5CB8.6060508@gmx.net> Robert R. schrieb: > Hello, > > i would like to write a piece of code to help me to align some sequence > of words and suggest me the ordered common subwords of them > > s0 = "this is an example of a thing i would like to have".split() > s1 = "another example of something else i would like to have".split() > s2 = 'and this is another " example " but of something ; now i would > still like to have'.split() > ... > alist = (s0, s1, s2) > > result should be : ('example', 'of', 'i', 'would', 'like', 'to', 'have' > > but i do not know how should i start, may be have you a helpful > suggestion? > a trouble i have if when having many different strings my results tend > to be nothing while i still would like to have one of the, or maybe, > all the best matches. > > best. > As far as I can see, you want to have the words, that all three lists have in common, right? s0 = "this is an example of a thing i would like to have".split() s1 = "another example of something else i would like to have".split() s2 = 'and this is another " example " but of something ; now i would still like to have'.split() def findCommons(s0, s1, s2): res = [] for word in s0: if word in s1 and word in s2: res.append(word) return res >>>print findCommons(s0,s1,s2) ['example', 'of', 'i', 'would', 'like', 'to', 'have'] From ajones1 at gmail.com Wed Nov 29 11:41:45 2006 From: ajones1 at gmail.com (Adam Jones) Date: 29 Nov 2006 08:41:45 -0800 Subject: why would anyone use python when java is there? In-Reply-To: <1164764454.043697.125730@j72g2000cwa.googlegroups.com> References: <1164762232.220759.57160@h54g2000cwb.googlegroups.com> <1164764454.043697.125730@j72g2000cwa.googlegroups.com> Message-ID: <1164818505.696250.264070@h54g2000cwb.googlegroups.com> gregarican wrote: > gavino wrote: > > wtf > > You have to be trolling I would think. Yeah, gavino has been trolling comp.lang.lisp for quite some time. For the life of me I can't understand why he would troll comp.lang.python when comp.lang.lisp is there. -Adam From writetosrj at gmail.com Fri Nov 24 08:00:53 2006 From: writetosrj at gmail.com (srj) Date: 24 Nov 2006 05:00:53 -0800 Subject: NFS server Message-ID: <1164373253.607159.26260@j44g2000cwa.googlegroups.com> i wish to develop an NFS server usin python from scratch( some wise guy told me i'ts easy!). can i get any kinda tutorial for this?? any suggestions on how 2 begin? From fredrik at pythonware.com Thu Nov 23 08:28:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Nov 2006 14:28:45 +0100 Subject: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]? References: Message-ID: Tor Erik Soenvisen wrote: > I've seen code like this: > > if type([]) is list: > print 'Is list' > > which seem to work. And also I've seen "var is None", as you mention. None is guaranteed to be a singleton: http://effbot.org/pyref/type-none.htm Why "is" works for type objects should be pretty obvious, of course. From e0427417 at student.tuwien.ac.at Sat Nov 25 14:57:24 2006 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Sat, 25 Nov 2006 20:57:24 +0100 Subject: my small hashlib - using pythons hash-functions Message-ID: <45689fae$0$11868$3b214f66@tunews.univie.ac.at> Hi. I wrote a small hashlib for C. Because I'm new to hashes I looked at pythons implementation and reused *some* of the code... or more the mathematical "hash-function", not really the code. In particular I looked at pythons hash and lookup functions, so I came up with this (see the code underneath). So, can this code be considered as derived and do I have to put my code under the GPL? I'd like to publish it under something less restrictive, like a BSD style license. But if GPL is the only way, then GPL it is. :) -panzi #define PERTURB_SHIFT 5 static ENTRY_T * lookup(CONTAINER_T * table, hash_const_str_t key, int (*loop_cond)(ENTRY_T * ptr, hash_const_str_t key)) { register ENTRY_T * entries = table->entries; register hash_size_t size = table->size; register hash_size_t pos = hash(key) % size; register hash_size_t perturb = pos; register ENTRY_T * ptr = entries + pos; while(loop_cond(ptr,key)) { pos = ((pos << 2) + pos + perturb + 1) % size; perturb >>= PERTURB_SHIFT; ptr = entries + pos; #ifdef HASH_COUNT_COLLISIONS ++ table->collisions; #endif } return ptr; } hash_t hash(register hash_const_str_t str) { /* python 2.5's hash function: */ register hash_size_t len; register hash_t h; assert(str); len = strlen(str); h = *str << 7; while (*str) h = (1000003 * h) ^ *str ++; h ^= len; return h; } From fredrik at pythonware.com Sun Nov 12 18:08:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Nov 2006 00:08:25 +0100 Subject: Random image text generation? In-Reply-To: <17751.42143.36842.842728@montanaro.dyndns.org> References: <17751.42143.36842.842728@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > Another possibility is to run the submissions through SpamBayes and silently > direct any which score as "unsure" or "spam" to me for review. Users > wouldn't even need to know their submissions were being scrutinized. there's also: http://akismet.com/ python interface here: http://kemayo.wordpress.com/2005/12/02/akismet-py/ From timr at probo.com Fri Nov 17 15:40:57 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 17 Nov 2006 12:40:57 -0800 Subject: how to print pdf with python on a inkjet printer. In-Reply-To: References: Message-ID: <455E1E59.4030501@probo.com> krishnakant Mane wrote: >> > double wow! as it is my customer wants me to print to the default > printer. > can you please help me with the command for rendering the pdf to the > printer with acrobat using python? You'll have to use the registry to find "acrord32", but once you find it, you just do: os.system( "\\Program Files\\Adobe\\Acrobat 7.0\\Reader\acrord32.exe /p xxx.pdf" ) The /p switch requests printing. > that essentially solves my most important problem. > else I was thinking to create an excel spreadsheet as a last alternative. > out of my curocity, I want to know if there are libraries that can > create excel spreadsheets? There are several ways. One way is to just bring up Excel itself and send it commands via COM. Several times, I've written my data as a comma-separated file (which Excel understands), then brought up Excel as a COM component, loaded the file, then used Excel commands to format the columns. There are also a couple of Python modules which purport to be able to read and write .xls files directly. There's xlrd, but there's a newer one whose name escapes me. I thought it was a pun, like "xlerator," but that's not right. > I also wanted to know if there is a common dialog for listing out > printers under windows? > so in future if I make this software in GUI, I can at list help the > user select the printer from the list. Yes, there is a standard "print" dialog for Windows that shows you the familiar dialog, with the list of printers and all of the options. In wxPython, I believe it is called wx.PrintDialog. In Pywin32, win32print.EnumPrinters can give you the list of available printers. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From walterbyrd at iname.com Wed Nov 15 10:52:23 2006 From: walterbyrd at iname.com (walterbyrd) Date: 15 Nov 2006 07:52:23 -0800 Subject: Python v PHP: fair comparison? In-Reply-To: <4run7sFskcrrU1@mid.individual.net> References: <1163533126.857007.206300@i42g2000cwa.googlegroups.com> <4run7sFskcrrU1@mid.individual.net> Message-ID: <1163605942.995212.34630@m73g2000cwd.googlegroups.com> Bjoern Schliessmann wrote: > walterbyrd wrote: > > > - PHP has a lower barrier to entry > > Which kind of barrier do you mean -- syntax, availability, ...? > Putting php into a web-site is as easy as throwing some php code into a my html file, and maybe giving the file a php extension. I can get php hosting for $10 a year easy. This may not be what you want for a major developement project, but the barrier to entry is very low. From fredrik at pythonware.com Sat Nov 18 12:34:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 18 Nov 2006 18:34:30 +0100 Subject: Python v PHP for web, and restarting Apache? In-Reply-To: <1163868294.131526.308080@e3g2000cwe.googlegroups.com> References: <1163783247.077263.8590@j44g2000cwa.googlegroups.com> <1163810800.915170.48580@e3g2000cwe.googlegroups.com> <1163868294.131526.308080@e3g2000cwe.googlegroups.com> Message-ID: walterbyrd wrote: >> Python is much better suited to writing and mainting large web >> applications though. > > I have to ask: why is that? modularity, modularity, and modularity. From skip at pobox.com Mon Nov 13 17:16:35 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 13 Nov 2006 16:16:35 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: <4558D443.1030802@hobbshouse.org> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <4554D416.70408@hobbshouse.org> <4554ECBF.7040603@hobbshouse.org> <4558BEC3.3020003@hobbshouse.org> <4558D443.1030802@hobbshouse.org> Message-ID: <17752.61123.582522.727445@montanaro.dyndns.org> Mike> But so far, the only response that I've received is that there's Mike> that ABC study somewhere and that settles that. In the absence of a later study that refutes the ABC work, I think it's best left alone. Skip From pavlovevidence at gmail.com Sun Nov 19 19:11:43 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 19 Nov 2006 16:11:43 -0800 Subject: re.match -- not greedy? References: Message-ID: <1163981503.295521.7180@m7g2000cwm.googlegroups.com> EXI-Andrews, Jack wrote: > the '*' and '+' don't seem to be greedy.. they will consume less in > order to match a string: > > >>> import re;re.match('(a+)(ab)','aaab').groups() > ('aa', 'ab') > > this is the sort of behaviour i'd expect from > '(a+?)(ab)' > > a+ should greedily consume a's at the expense of the string not matching It's called backtracking. If a match fails, the regexp engine recursively unwinds some of the greedy matching and tries again. > in real life, i am trying to match #defines: > > >>> re.match( '#define ([A-Za-z0-9_]+)([^(])', '#define > abc(d)').groups() > ('ab', 'c') > > i want this example to fail because the first character after a string > of letters is a '(' > i want to match only #defines without parameters. Probably the easiest thing to do is to attempt to match zero or one opening parentheses, and bail out if it did end up matching the parenthesis. m = re.match(r"#define ([A-Za-z0-9_]+)(\(?)","#define abc(d)") if m and m.groups(2) != "(": ... (BTW, it's good practice to use a raw strings for the regular expressions as I did.) > so what's the definition of greedy? It means match as much you can *while getting a match*. Just remember regexp parsing is not a one way street: if it hits a dead end, it'll go back and try another path. In fact, greediness usually doesn't affect *whether* a regexp matches; it only affects the groupings. I'm suddenly curious if there are any cases at all where greediness changes whether it finds a match. > (pls copy me on responses) Ah, too bad you won't see it then.... Carl Banks From rpdooling at gmail.com Sun Nov 19 09:15:38 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 19 Nov 2006 06:15:38 -0800 Subject: How do I stop Python IDLE (GUI) from immediately exiting when I enter it? In-Reply-To: <1163921048.878108.145810@j44g2000cwa.googlegroups.com> References: <1163921048.878108.145810@j44g2000cwa.googlegroups.com> Message-ID: <1163945738.624543.37730@k70g2000cwa.googlegroups.com> John (Z R) L wrote: > But after clicking "run module" Being new is never problem, but do learn to provide concise, complete descriptions of exactly what happened and what you were doing at the time. Are you in IDLE? Or are you in PythonWin? OR did you make a script file and try to run it by double clicking on it? Sounds like you were creating a script file, then tried to run it? Search this list at Google Groups comp.lang.python for "keep DOS box open." http://tinyurl.com/wh7fy > Another problem I have is firewall. On my old computer (Windows 98) > when using Python GUI, it can't run modules because of some firewall. Please enter the exact error message you get. It's probably some officious Windows security glitch, but nobody can help you until you provide the messages you get. Windows 98? Linux would run twice as fast on any machine old enough to run Windows 98, and your Python would work better, too. Good luck, rd From rridge at csclub.uwaterloo.ca Sun Nov 5 06:06:33 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 5 Nov 2006 03:06:33 -0800 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <454bd36c$0$2364$9b622d9e@news.freenet.de> <454ca6b4$0$151$9b622d9e@news.freenet.de> <7xpsc33zmh.fsf@ruckus.brouhaha.com> <454d587d$0$4361$9b622d9e@news.freenet.de> <7x7iyafg85.fsf@ruckus.brouhaha.com> Message-ID: <1162724793.506671.35730@i42g2000cwa.googlegroups.com> Paul Rubin wrote: > I dunno about x86 hardware signals but these instructions do > read-modify-write operaitons. That means there has to be enough > interlocking to prevent two cpu's from updating the same memory > location simultaneously, which means the CPU's have to communicate. > See (I think this is > how the current x86's do it): The MESI protocol is used to ensure all read and write operations are cache coherent, not just locked read-modify-write operations. Whether the LOCK prefix is used or not in an instruction normally isn't externally visable. From IA-32 Intel? Architecture Software Developer's Manual Volume 3A: System Programming Guide, Part 1: For the Pentium 4, Intel Xeon, and P6 family processors, if the area of memory being locked during a LOCK operation is cached in the processor that is performing the LOCK operation as write-back memory and is completely contained in a cache line, the processor may not assert the LOCK# signal on the bus. Instead, it will modify the memory location internally and allow it's cache coherency mechanism to insure that the operation is carried out atomically. This operation is called "cache locking." The cache coherency mechanism automatically prevents two or more processors that have cached the same area of memory from simultaneously modifying data in that area. The cost of mantaining cache coherency for a locked increment instruction should be no different than that of an unlocked increment instruction. Ross Ridge From stanc at al.com.au Fri Nov 17 03:40:49 2006 From: stanc at al.com.au (Astan Chee) Date: Fri, 17 Nov 2006 19:40:49 +1100 Subject: popen(1-4) as a seperate process In-Reply-To: References: <455D3F18.40902@al.com.au> <455D5EFE.40803@al.com.au> Message-ID: <455D7591.1070607@al.com.au> Dennis Lee Bieber wrote: > On Fri, 17 Nov 2006 18:53:41 +1100, Astan Chee > declaimed the following in comp.lang.python: > > > >> What would be a good method to do this? I've tried your >> os.system("command&") and the spawned process is still the child of the >> current running process (which is not what I want to happen). >> Thanks again and sorry for the confusion. >> > > The & trailer is UNIX/LINUX specific for detaching a process. There > may be other commands needed for Windows. Especially as, I think, the & > syntax can create processes that remain running even if the user logs > off... Something Windows doesn't really support. > > Windows os.startfile(...) MIGHT do what you want > Yes I know & works in unix/linux; I thought it worked in windows also. But thanks, os.startfile() worked perfectly. Cheers From john at castleamber.com Wed Nov 15 22:08:55 2006 From: john at castleamber.com (John Bokma) Date: 16 Nov 2006 03:08:55 GMT Subject: Will GPL Java eat into Python marketshare? References: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> <455bb047$0$28561$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > John Bokma a ?crit : >> Harry George wrote: >> >> >>>Short answer: People use Python instead of Java because people (at >>>least intelligent people) tend to avoid pain. >> >> >> Intelligent people don't suffer from fanboy sentiments. They just >> pick a language that works best for them. >> > Which is *exactly* what Harry said... No, there is a very clear difference if one is willing to see it. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From ddvlad at gmail.com Tue Nov 14 16:00:35 2006 From: ddvlad at gmail.com (Vlad Dogaru) Date: 14 Nov 2006 13:00:35 -0800 Subject: BaseHTTPServer - getting POST parameters Message-ID: <1163538035.160424.3470@e3g2000cwe.googlegroups.com> Hello, After experimenting for a while, I am still not able to find where the POST data is in the BaseHTTPRequestHandler class. I am trying to write a very simple HTTP server for a project of mine and I need to get the POST data. Certainly I am missing something, as it is a comon task. Thanks in advance, Vlad From george.sakkis at gmail.com Mon Nov 13 10:51:58 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 13 Nov 2006 07:51:58 -0800 Subject: Python development time is faster. References: <1163425734.640509.99420@m73g2000cwd.googlegroups.com> Message-ID: <1163433118.770742.262140@e3g2000cwe.googlegroups.com> Steven Bethard wrote: > A simple example from document indexing. Using Java Lucene to index > some documents, you'd write code something like:: > > Analyzer analyzer = new StandardAnalyzer() > IndexWriter writer = new IndexWriter(store_dir, analyzer, true) > for (Value value: values) { > Document document = Document() > Field title = new Field("title", value.title, > Field.Store.YES, > Field.Index.TOKENIZED) > Field text = new Field("text", value.text, > Field.Store.YES, > Field.Index.TOKENIZED) > document.add(title) > document.add(text) > } > > Why is this code so verbose? Because the Lucene Java APIs don't like > useful defaults. So for example, even though StandardAnalyzer is > supposedly *Standard*, there's no IndexWriter constructor that includes > it automatically. Similarly, if you create a Field with a string name > and value (as above), you must specify both a Field.Store and a > Field.Index - there's no way to let them default to something reasonable. > > Compare this to Python code. Unfortunately, PyLucene wraps the Lucene > APIs pretty directly, but I've wrapped PyLucene with my own wrapper that > adds useful defaults (and takes advantages of things like Python's > **kwargs). Here's what the same code looks like with my Python wrapper > to Lucene:: > > writer = IndexWriter(store_dir) > for value in values: > document = Document(title=value.title, text=value.text)out two > writer.addDocument(document) > writer.close() > > Gee, and I wonder why it took me so much longer to write things in Java. ;-) Oh, the memories... I went down the same road about two years ago, though I didn't know about PyLucene at the time and wrapped in jython the parts of Lucene I used... never bothered to deal with java's verbosity after that. It's a pity that jython resembles abandon-ware these days, when jRuby showed up pretty recently and is gaining in penetration with the java crowd. It will be a non-trivial loss for python if it is left behind in the JVM world (at least if the latter is not swallowed by the .NET dark forces, which doesn't seem to happen any time soon ;-). George From no at spam.com Wed Nov 1 16:21:20 2006 From: no at spam.com (Farshid Lashkari) Date: Wed, 01 Nov 2006 13:21:20 -0800 Subject: Hooking file open In-Reply-To: References: Message-ID: Dale Strickland-Clark wrote: > You might consider trapping calls to file() too, which is an alias for > open(). Thanks, I didn't know about that. > Also, I think I'd do my logging before calling the real function. It depends > how you want to deal with exceptions. I placed the logging after the call to the real function so that files that don't exist will not be logged. However, I'm already checking for file existence during the post process of the script running, so I guess it doesn't really make too much of a difference. Thanks for the help. -Farshid From johnjsal at NOSPAMgmail.com Tue Nov 14 10:41:53 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 14 Nov 2006 10:41:53 -0500 Subject: refactoring so that multiple changes can be made with one variable? Message-ID: <4559e396$0$32430$c3e8da3@news.astraweb.com> My code is below. For now I'm focusing on the lines where health (and armor) are increased in each character class. Let's say I decided to change the amount of increase in the future. As it is now, I'd have to go to each character class and change the number so that each is still in a good relation to the other (right now: 3, 2, 1; later: perhaps 4, 3, 2, 1, if I added a new class -- i.e., change Fighter from 3 to 4, Thief from 2 to 3, in other words increase them all by 1). So instead of changing each one, is there a simple, clean way of just changing a single number so that this change is reflected in all classes? Hope that makes sense. class Character(object): def __init__(self, name, strength, dexterity, intelligence): self.name = name self.health = 10 self.armor = self.attack = self.defense = self.magic_attack = \ self.magic_defense = 0 self.strength = strength self.dexterity = dexterity self.intelligence = intelligence self.adjust_attributes() def adjust_attributes(self): pass class Fighter(Character): def adjust_attributes(self): self.health += 3 self.armor += 3 self.attack += 2 self.defense += 2 self.strength += 1 class Thief(Character): def adjust_attributes(self): self.health += 2 self.armor += 2 self.attack += 1 self.defense += 1 self.magic_defense += 1 self.dexterity += 1 class Mage(Character): def adjust_attributes(self): self.health += 1 self.armor += 1 self.magic_attack += 2 self.magic_defense += 2 self.intelligence += 1 From spe.stani.be at gmail.com Thu Nov 30 05:34:02 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 30 Nov 2006 02:34:02 -0800 Subject: SPE refuses. In-Reply-To: References: <1164828687.755193.4900@l39g2000cwd.googlegroups.com> <1164842145.465496.135210@h54g2000cwb.googlegroups.com> Message-ID: <1164882842.357607.75440@16g2000cwy.googlegroups.com> On 30 nov, 10:50, egbert wrote: > On Wed, Nov 29, 2006 at 03:15:45PM -0800, SPE - Stani's Python Editor wrote:> Do you have python-wxversion installed? > > > $sudo apt-get install python-wxversionThat helped. But why isn't it included in the wxPython download ? I was surprised as well. I filed a bug report at debian MOTU that spe depends as well on python-wxversion, so that it is automatically installed together with spe in the future. > Anyway, the first screen looks great. I will explore spe. > Thanks. You're welcome! Stani From environ314 at gmail.com Wed Nov 22 15:11:44 2006 From: environ314 at gmail.com (Dan) Date: 22 Nov 2006 12:11:44 -0800 Subject: utf - string translation In-Reply-To: <1164224962.711265.198090@h48g2000cwc.googlegroups.com> References: <1164224962.711265.198090@h48g2000cwc.googlegroups.com> Message-ID: <1164226304.119425.206380@h54g2000cwb.googlegroups.com> Thank you for your answers. In fact, I'm getting start with Python. I was looking for transform a text through elementary cryptographic processes (Vigen?re). The initial text is in a file, and my system is under UTF-8 by default (Ubuntu) From steve at holdenweb.com Mon Nov 6 14:28:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Nov 2006 14:28:59 -0500 Subject: forwarding *arg parameter In-Reply-To: <%oG3h.107$8a7.65@read3.inet.fi> References: <6pn3h.125$7b6.98@read3.inet.fi> <2Fp3h.195$7b6.100@read3.inet.fi> <%oG3h.107$8a7.65@read3.inet.fi> Message-ID: Tuomas wrote: > Steven D'Aprano wrote: > >>On Sun, 05 Nov 2006 19:35:58 +0000, Tuomas wrote: >> >> >> >>>Thanks. My solution became: >>> >>> >>>>>>def flattern(arg): >>> >>>... result = [] >>>... for item in arg: >>>... if isinstance(item, (list, tuple)): >>>... result.extend(flattern(item)) >>>... else: >>>... result.append(item) >>>... return tuple(result) >>>... >>> >>>>>>def g(*arg): >>> >>>... arg = flattern(arg) >>>... return arg >>>... >>> >>>>>>def f(*arg): >>> >>>... return g(arg) >>>... >>> >>>>>>f('foo', 'bar') >>> >>>('foo', 'bar') >> >> >> >>That's the most complicated do-nothing function I've ever seen. Here is a >>shorter version: >> >>def shortf(*args): >> return args >> >> >> >> >>>>>f('foo', 'bar') >> >>('foo', 'bar') >> >> >>>>>shortf('foo', 'bar') >> >>('foo', 'bar') >> >> >> >>>>>f(1,2,3,4) >> >>(1, 2, 3, 4) >> >> >>>>>shortf(1,2,3,4) >> >>(1, 2, 3, 4) >> >> >> >>>>>f({}, None, 1, -1.2, "hello world") >> >>({}, None, 1, -1.2, 'hello world') >> >> >>>>>shortf({}, None, 1, -1.2, "hello world") >> >>({}, None, 1, -1.2, 'hello world') >> >>Actually, they aren't *quite* identical: your function rips lists apart, >>which is probably not a good idea. >> >> >> >>>>>f("foo", [1,2,3], None) # three arguments turns into five >> >>('foo', 1, 2, 3, None) >> >> >>>>>shortf("foo", [1,2,3], None) # three arguments stays three >> >>('foo', [1, 2, 3], None) >> >> >> >>I still don't understand why you are doing this. Can we have an example of >>why you think you need to do this? > > > If i redefine the function g the difference comes visible: > > >>> def g(*arg): > .... if with_flattern: arg=flattern(arg) > .... return arg > > >>> with_flattern=False > >>> f('foo', 'bar') > (('foo', 'bar'),) > >>> with_flattern=True > >>> f('foo', 'bar') > > If you read the whole chain you find out what we were talking of. > > TV Suppose you did actually want to do this you have chosen about the worst possible way: the use of global variables to condition function execution is a sure way to get into trouble. Consider if somebody else want to use your function: they also have to set a global in their program to avoid your function raising an exception. Fortunately Python has just the thing to make such horrors unnecessary: the default argument value. Try something like this (untested): def g(flattening=True, *arg): if flattening: arg = flatten(arg) return arg Obviously you could use either True or False for the default value. In the case above the function flattens by default. You could also, if you wished, have f() take the flattening argument, and always pass it to g(). Nothing very sophisticated here, just something to help you flex your growing Python and programming muscles. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From prouleau001 at gmail.com Thu Nov 16 11:03:48 2006 From: prouleau001 at gmail.com (prouleau001 at gmail.com) Date: 16 Nov 2006 08:03:48 -0800 Subject: atexit.register does not return the registered function. IMHO, it should. Message-ID: <1163693028.543926.163320@f16g2000cwb.googlegroups.com> Hi all! Since that the decorator syntax is upon us, I think it would be good if atexit.register() was returning the function passed as argument. This simple change to the library would solve a problem with the use of atexit.register as a decorator (and I can't think of any use case where this change would break any code). I describe the problem in the following text. Problem using atexit.register as a decorator ============================================ In his April 2005 article titled `Python 2.4 Decorators: Reducing code duplication and consolidating knowledge`_ , Phillip Eby describes how you can use `atexit.register()`_ from the standard Python library. He shows how to use the decorator syntax to register a function that will execute at program termination. Here is how it goes:: @atexit.register def goodbye(): print "Goodbye, terminating..." However, there is one fundamental problem with this: atexit.register() returns None. Since the above code corresponds to:: def goodbye(): print "Goodbye, terminating..." goodbye = atexit.register(goodbye) the code registers goodbye but right after it binds goodbye to None! You can see this in the following session:: >>> import atexit >>> @atexit.register ... def goodbye(): ... print "Goodbye, terminating..." ... >>> goodbye() Traceback (most recent call last): File "", line 1, in ? TypeError: 'NoneType' object is not callable >>> >>> goodbye >>> type(goodbye) >>> There is two solutions to this problem: 1. Use another function to register and decorate. 2. Change atexit.register() in the Python library so that it returns the function it registers. Solution 1 can be implemented right away:: def atexit_register(fct): atexit.register(fct) return fct @atexit_register def goodbye2(): print "Goodbye 2!!" and it works: it registers the function for execution at termination but leaves goodbye2 callable:: >>> def atexit_register(fct): ... atexit.register(fct) ... return fct ... >>> @atexit_register ... def goodbye2(): ... print "Goodbye 2!!" ... >>> goodbye2() Goodbye 2!! >>> goodbye2 >>> .. References .. _atexit.register(): http://www.python.org/doc/current/lib/module-atexit.html .. _Python 2.4 Decorators\: Reducing code duplication and consolidating knowledge: http://www.ddj.com/184406073 From greenbergj at NOSPAMwit.edu Mon Nov 27 13:50:53 2006 From: greenbergj at NOSPAMwit.edu (Jordan Greenberg) Date: Mon, 27 Nov 2006 13:50:53 -0500 Subject: python skipping lines? In-Reply-To: <1164651477.588728.294490@14g2000cws.googlegroups.com> References: <1164651477.588728.294490@14g2000cws.googlegroups.com> Message-ID: <456B338D.4050408@NOSPAMwit.edu> lisa.engblom at gmail.com wrote: > Hi, > Any ideas of what could be the problem? > Hard to say without seeing your code. Jordan Greenberg -- Posted via a free Usenet account from http://www.teranews.com From tgrav at mac.com Thu Nov 16 15:35:00 2006 From: tgrav at mac.com (Tommy Grav) Date: Thu, 16 Nov 2006 15:35:00 -0500 Subject: pyfits problem Message-ID: <4509DD3E-5112-409C-B0E0-07649E6DC12B@mac.com> I am trying to load in a fits-image and get this error wiyn05dec/n1 -> display -i obj062.fits Traceback (most recent call last): File "/Users/tgrav/Work/Astronomy/MyCode/Python/Redspit/ display.py", line 48, in ? main() File "/Users/tgrav/Work/Astronomy/MyCode/Python/Redspit/ display.py", line 30, in main im = pyfits.getdata(options.infname) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/pyfits/NP_pyfits.py", line 4645, in getdata _data = hdu.data File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/pyfits/NP_pyfits.py", line 2058, in __getattr__ self.data = np.array(raw_data, type=np.Float32) AttributeError: 'module' object has no attribute 'Float32' I am using numpy 1.0rc3 and ActivePython 2.4.3 Build 11. Anyone know what is going on? Cheers Tommy From ronrsr at gmail.com Sun Nov 19 05:14:45 2006 From: ronrsr at gmail.com (ronrsr) Date: 19 Nov 2006 02:14:45 -0800 Subject: Why isn't SPLIT splitting my strings Message-ID: <1163931285.390782.130500@h54g2000cwb.googlegroups.com> I'm trying to break up the result tuple into keyword phrases. The keyword phrases are separated by a ; -- the split function is not working the way I believe it should be. Can anyone see what I"m doing wrong? bests, -rsr- print "newstring =", str(result[i][0]) print "just split", str(result[i][0]).split('; ()[]"') zd.append(str(result[i][0]).split('; ()[]"')) result= (('Agricultural subsidies; Foreign aid',), ('Agriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development, Birth Defects; Toxic Chemicals',), ('Antibiotics, Animals',), ('Agricultural Subsidies, Global Trade',), ('Agricultural Subsidies',), ('Biodiversity',), ('Citizen Activism',), ('Community Gardens',), ('Cooperatives',), ('Dieting',), ('Agriculture, Cotton',), ('Agriculture, Global Trade',), ('Pesticides, Monsanto',), ('Agriculture, Seed',), ('Coffee, Hunger',), ('Pollution, Water, Feedlots',), ('Food Prices',), ('Agriculture, Workers',), ('Animal Feed, Corn, Pesticides',), ('Aquaculture',), ('Chemical Warfare',), ('Compost',), ('Debt',), ('Consumerism',), ('Fear',), ('Pesticides, US, Childhood Development, Birth Defects',), ('Corporate Reform, Personhood (Dem. Book)',), ('Corporate Reform, Personhood, Farming (Dem. Book)',), ('Crime Rates, Legislation, Education',), ('Debt, Credit Cards',), ('Democracy',), ('Population, World',), ('Income',), ('Democracy, Corporate partial results: string a = Agricultural subsidies; Foreign aid newstring = Agricultural subsidies; Foreign aid just split ['Agricultural subsidies; Foreign aid'] newstring = Agriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development, Birth Defects; Toxic Chemicals just split ['Agriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development, Birth Defects; Toxic Chemicals'] newstring = Antibiotics, Animals just split ['Antibiotics, Animals'] From fredrik at pythonware.com Fri Nov 17 12:39:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 17 Nov 2006 18:39:29 +0100 Subject: Slicing / subsetting list in arbitrary fashion In-Reply-To: <455DEA24.1060906@lind-beil.net> References: <455DEA24.1060906@lind-beil.net> Message-ID: Gregg Lind wrote: > One difficulty I am having with using Python for scientific computing is > that I cannot figure out good ways to get arbitrary (unpatterned?) slices. > In Python, solutions I have found for these tasks are: > > [vals[ii] for ii in wanted] # task 1 > > [a[1] for in zip(Truths,vals) if a[0] ] # task 2 array objects have "take" and "put" methods; see e.g. (random google link): http://stsdas.stsci.edu/numarray/Doc/node33.html From nateastle at gmail.com Sat Nov 18 10:08:47 2006 From: nateastle at gmail.com (nateastle at gmail.com) Date: 18 Nov 2006 07:08:47 -0800 Subject: basic python questions In-Reply-To: <18C7h.72$_H5.25@tornado.texas.rr.com> References: <1163829271.660193.70450@j44g2000cwa.googlegroups.com> <18C7h.72$_H5.25@tornado.texas.rr.com> Message-ID: <1163862527.042015.63400@k70g2000cwa.googlegroups.com> I am currently going to school at Utah Valley State College, the course that I am taking is analysis of programming languages. It's an upper division course but our teacher wanted to teach us python as part of the course, he spent about 2 - 3 weeks on python which has been good. I currently work with .net and it is fun to see what other languages have and what sytax they use. Paul McGuire wrote: > wrote in message > news:1163829271.660193.70450 at j44g2000cwa.googlegroups.com... > >I have a simple assignment for school but am unsure where to go. The > > assignment is to read in a text file, split out the words and say which > > line each word appears in alphabetical order. I have the basic outline > > of the program done which is: > > > > And in general, this is one of the best "can anyone help me with my > homework?" posts I've ever seen. > A. You told us up front that it was your homework. > B. You made an honest stab at the solution before posting, and posted the > actual code. > C. You ended with some specific questions on things that didn't work or that > you wanted to improve. > > Your current program looks like at least A- material. Add use of sorted and > enumerate, and handle that exception a little better, and you're getting > into A+ territory. > > Out of curiosity, what school are you attending that is teaching Python, and > under what course of study? > > -- Paul From sjmachin at lexicon.net Mon Nov 13 00:37:59 2006 From: sjmachin at lexicon.net (John Machin) Date: 12 Nov 2006 21:37:59 -0800 Subject: how do i map this? In-Reply-To: <1163387481.135930.167580@m7g2000cwm.googlegroups.com> References: <1163387481.135930.167580@m7g2000cwm.googlegroups.com> Message-ID: <1163396278.936455.48200@h54g2000cwb.googlegroups.com> ronrsr wrote: > I think I am passing the wrong argument to the Print_row routine: Well, yes, that is what the error message is telling you. It is also what Fredrik Lundh told you only a couple of hours ago. He also told you what to do to fix it, at a high level. Below is my attempt to explain at a lower level. If you don't understand, please *reply* to my message; *don't* start a new topic as though it were a totally fresh problem. Now read on ... > > > > Traceback (most recent call last): > File "index.py", line 91, in ? > zhtml.print_row(record) > File "/usr/www/users/homebase/realprogress/zingers/zhtml.py", line > 154, in pri > nt_row > print """ > TypeError: format requires a mapping > homebase at upsilon% > > > > routine from zhtml.py: > > #row is a dictionary with keys: zid, keywords, citation, quotation > def print_row(row): > print """ > %(keywords)s > > %(quotation)s > > %(citation)s > >

name="updateform" enctype="application/x-www-form-urlencoded" > method="GET"> type="submit" value="Edit">
> > > """ This cannot be the code that was executed -- it would need to be followed by % row for it to produce the error message that you received. > > > code from index.py: > > > cursor.execute(querystring); > # get the resultset as a tuple > result = cursor.fetchall() > # iterate through resultset > for record in result: > print record[0] , "-->", record[1] "record" looks like a tuple, not a dictionary. > > #zq = zc.query(querystring).dictresult() > > #HTML > > import zhtml > zhtml.print_start_html() > zhtml.print_header("Frankie's Zingers") > > if form.has_key("printview"): > print ("xxxxthenxxxxxx") > zhtml.printp_start_table() > zhtml.printp_title_row() > for record in result: > zhtml.printp_row(record[row]) > else: > # print ("xxxxxelsexxxxx",record[1]); > zhtml.print_top_controls(k=k,c=c,q=q) > zhtml.print_start_table() > zhtml.print_title_row() > zhtml.print_search_row(k=k,c=c,q=q) > for record in result: > > > print(record); print is a statement, not a function; you meant print record Instead of that, do this print type(record) print repr(record) You will find that "record" is a tuple, not a dictionary Without changing the code in the zhtml module, you need to make a dictionary, for example (untested): adict = {} for key, inx in zip("zid keywords citation quotation".split(), (0, 1, 2, 3)): adict[key] = record[inx] zhtml.print_row(adict) where (0, 1, 2, 3) are the positions of the 4 fields in record -- change the numbers as necessary to match reality. Alternatively (sketch): (1) unpack the tuple e.g. zid, keywords, citation, quotation = record # Add names for any other fields that exist. # Change the order as necessary to match reality. (2) call a changed zhtml routine: zhtml.print_row(zid, keywords, citation, quotation) (3) re-jig the zhtml.print_row routine def print_row(zid, keywords, citation, quotation): print """ %s %s etc etc """ % (keywords, quotation, citation, zid) > zhtml.print_row(record) > > zhtml.print_end_table() > zhtml.print_end_html() HTH, John From fredrik at pythonware.com Thu Nov 16 06:22:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Nov 2006 12:22:29 +0100 Subject: split CSV fields In-Reply-To: <1163675506.590469.251910@h48g2000cwc.googlegroups.com> References: <1163674830.440318.246920@f16g2000cwb.googlegroups.com> <1163675506.590469.251910@h48g2000cwc.googlegroups.com> Message-ID: John Machin wrote: > Given Peter Otten's post, looks like > (1) there's a bug in the "fmtparam" mechanism -- it's ignoring the > escapechar in my first twiddle, which should give the same result as > Peter's. > (2) > | >>> csv.excel.doublequote > True > According to my reading of the docs: > """ > doublequote > Controls how instances of quotechar appearing inside a field should be > themselves be quoted. When True, the character is doubled. When False, > the escapechar is used as a prefix to the quotechar. It defaults to > True. > """ > Peter's example should not have worked. the documentation also mentions a "quoting" parameter that "controls when quotes should be generated by the writer and recognised by the reader.". not sure how that changes things. anyway, it's either unclear documentation or a bug in the code. better submit a bug report so someone can fix one of them. From jorge.vargas at gmail.com Fri Nov 10 09:52:25 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Fri, 10 Nov 2006 10:52:25 -0400 Subject: manual eggs downloads? In-Reply-To: References: Message-ID: <32822fe60611100652u63430d6cm4c9f405b1a28e10d@mail.gmail.com> On 11/10/06, Harry George wrote: > "eggs" are wonderful for no-hassle get-all-the-dependencies. However, > they can trigger hands-off downloads from various sites. This is Bad > News for corporate environments in which every download is carefully > pre-approved. > > A tarball with a subdirectory of "third_party" packages is ok. A web > page simple listing the third party sites and the recommended > downloads is ok. Automatically downloading is not ok. > > Is there some way in the eggs mechanism to just get a list of the > proposed downloads, and let the user take the actions manually? > that is not implemented yet, also you may want to take this to the distutils-sig list. what you can do is read the egg's setup.py for it's dependencies, but this can turn into something like red hat's dep hell. > -- > Harry George > PLM Engineering Architecture > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at holdenweb.com Mon Nov 6 21:19:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Nov 2006 21:19:20 -0500 Subject: assigning values in __init__ In-Reply-To: <454faf57$0$12993$c3e8da3@news.astraweb.com> References: <454faf57$0$12993$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Let's say I'm making a game and I have this base class: > > class Character(object): > > def __init__(self, name, stats): > self.name = name > self.strength = stats[0] > self.dexterity = stats[1] > self.intelligence = stats[2] > self.luck = stats[3] > > Is this a good way to assign the values to the different attributes? > Should 'stats' be a list/tuple (like this), or should I do *stats instead? > > I'm trying to think ahead to when I might want to add new attributes, > and I want to make sure this doesn't get crazy with individual > parameters instead of just the one list. > > Or maybe there's some way to loop through two lists (the stats and the > attributes) and assign them that way? I was thinking of a nested for > statement but that didn't seem to work. If your program deals with 4-element tuples then although you *could* use *stats in your calls to pass each element of the tuple as a single argument, that's not really necessary. A way to write the initializations you want without using indexing is: class Character(object): def __init__(self, name, stats): self.name = name self.strength, self.dexterity, \ self.intelligence, self.luck = stats regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bj_666 at gmx.net Mon Nov 6 05:11:41 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 06 Nov 2006 11:11:41 +0100 Subject: Python Distilled References: <1162790565.418382.237050@m73g2000cwd.googlegroups.com> Message-ID: In <1162790565.418382.237050 at m73g2000cwd.googlegroups.com>, Simon Wittber wrote: > I'd also like to remove any deprecated or stuff which is left in for > backwards functionality (eg Classic classes). Classic classes are still needed for exceptions: >>> class E(object): ... pass ... >>> raise E Traceback (most recent call last): File "", line 1, in TypeError: exceptions must be classes, instances, or strings (deprecated), not type Ciao, Marc 'BlackJack' Rintsch From mike.klaas at gmail.com Tue Nov 28 16:42:35 2006 From: mike.klaas at gmail.com (Klaas) Date: 28 Nov 2006 13:42:35 -0800 Subject: How to increase the speed of this program? In-Reply-To: <1164741116.583861.278220@l12g2000cwl.googlegroups.com> References: <1164699156.682944.97410@j44g2000cwa.googlegroups.com> <1164706548.778583.267730@n67g2000cwd.googlegroups.com> <1164714786.086910.288450@45g2000cws.googlegroups.com> <1164739788.335821.239100@n67g2000cwd.googlegroups.com> <1164741116.583861.278220@l12g2000cwl.googlegroups.com> Message-ID: <1164750155.735437.37680@n67g2000cwd.googlegroups.com> Klaas wrote: > In fact, you can make it about 4x faster by balancing: > > [klaas at worbo ~]$ python -m timeit -s "from array import array" > "array('c','\0'*200)*500" > 10000 loops, best of 3: 32.4 usec per loop This is an unclean minimally-tested patch which achieves reasonable performance (about 10x faster than unpatched python): $ ./python -m timeit -s "from array import array" "array('c', '\0')*100000" 10000 loops, best of 3: 71.6 usec per loop You have my permission to use this code if you want to submit a patch to sourceforge (it needs, proper benchmarking, testing, and tidying). -Mike Index: Modules/arraymodule.c =================================================================== --- Modules/arraymodule.c (revision 52849) +++ Modules/arraymodule.c (working copy) @@ -680,10 +680,29 @@ return NULL; p = np->ob_item; nbytes = a->ob_size * a->ob_descr->itemsize; - for (i = 0; i < n; i++) { - memcpy(p, a->ob_item, nbytes); - p += nbytes; - } + + if (n) { + Py_ssize_t chunk_size = nbytes; + Py_ssize_t copied = 0; + char *src = np->ob_item; + + /* copy first element */ + memcpy(p, a->ob_item, nbytes); + copied += nbytes; + + /* copy exponentially-increasing chunks */ + while(chunk_size < (size - copied)) { + memcpy(p + copied, src, chunk_size); + copied += chunk_size; + if(chunk_size < size/10) + chunk_size *= 2; + } + /* copy remainder */ + while (copied < size) { + memcpy(p + copied, src, nbytes); + copied += nbytes; + } + } return (PyObject *) np; } From sthompson at creativewebnet.com Fri Nov 24 10:48:15 2006 From: sthompson at creativewebnet.com (Steve Thompson) Date: Fri, 24 Nov 2006 10:48:15 -0500 Subject: Active State and Komodo... References: Message-ID: On Fri, 24 Nov 2006 06:35:21 -0500, Steve Thompson wrote: > Hello all, > > I was wondering the differnced there were betwee Active State's python and > the open source version of python. Would I have to unistall my opend souce > python? Additonally, how does Active State's Komodo IDE vs. the eric3 IDE > unler SuSE Linux v. 10.i? > > Addionally, is the eric IDE (version 3) an acceptible IDE or are there > more easy and more productive IDE's for perl? > > I'm urining Gnome v. 12.2.2 and Eric v 3.8.1 > > Thanks Steve Sorry, it was too early in the morning when I wrote this. The last 2 paragraphs should read "Addionally, is the eric IDE (version 3) an acceptible IDE or are there more easy and more productive IDE's for python?". "I'm using Gnome v. 12.2.2 and Eric v 3.8.1" Thanks again, Steve From duncan.booth at invalid.invalid Sun Nov 12 04:55:53 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Nov 2006 09:55:53 GMT Subject: explicit self revisited References: Message-ID: Dennis Lee Bieber wrote: > On Sun, 12 Nov 2006 01:55:35 +0100, Fredrik Lundh > declaimed the following in comp.lang.python: > > >> >> ah, good point. I've updated the FAQ. >> > Ah, but do we dare update the Wikipedia link to include Python as a > language capable of COMEFROM? Somebody definitely should. The current wikipedia article contains an example in a hypothetical dialect of BASIC ('because an actual example in INTERCAL would be too difficult to read'). Somebody should enhance the article with the equivalent example in Python which is both easy to read and can actually be run: from goto import goto, comefrom, label comefrom .repeat name = raw_input('what is your name? ') if name: print "Hello",name label .repeat print "Goodbye!" From elicriffield at gmail.com Mon Nov 13 11:11:28 2006 From: elicriffield at gmail.com (Eli Criffield) Date: 13 Nov 2006 08:11:28 -0800 Subject: tab compleation input Message-ID: <1163434288.421441.48320@f16g2000cwb.googlegroups.com> Here is what i want to do. I have a question in my program, and i want to do tab completion for the valid answers. Say i have : --snip-- validanswers = [ 'yes', 'no', 'maybe', 'tuesday', 'never' ] #and i ask sys.stdout.write("Answer the Question: ") answer = sys.stdin.readline().rstrip() if answer not in valid answers: print "Wrong!" --snip-- But what i want is when i enter the answer i can hit tab and it'll complete one of the validanswers I know i can do tab complete with readline and 'raw_input('> ')' but that's only to execute python commands right? Eli From wiggly at wiggly.org Tue Nov 14 09:20:07 2006 From: wiggly at wiggly.org (Nigel Rantor) Date: Tue, 14 Nov 2006 14:20:07 +0000 Subject: modules and generated code Message-ID: <4559D097.5090609@wiggly.org> Hi all, Python newbie here with what I hope is a blindingly obvious question that I simply can't find the answer for in the documentation. So, if I have a tool that generates python code for me (in my case, CORBA stubs/skels) in a particular package is there a way of placing my own code under the same package hierarchy without all the code living in the same directory structure. Ideally I would like something like the following: package_dir/ top_level_package/ generated_code_package/ implementation_code_package/ but have two distinct directories that hold them so that I can simply delete the generated code and regenerate it without worrying that anything got left behind. So, I want something like: generated_package_dir/ top_level_package/ generated_code_package/ implementation_package_dir/ top_level_package/ implementation_code_package/ Whilst I can create this structure, and add 'generated_package_dir' and 'implementation_package_dir' to PYTHONPATH the fact that both directories contain 'top_level_package' seems to be causing clashes, perhaps because there are multiple __init__.py files for 'top_level_package'? I know that this is possible in Java, Perl and C++ so I am finding it hard to believe I can't do the same in Python, I just think I'm too new to know how. I have spent most of this morning searching through all the docs I can find, searching on USENET and the web to no avail. Any help or pointers greatly appreciated. Regards, n From kibleur.christophe at gmail.com Thu Nov 23 04:36:56 2006 From: kibleur.christophe at gmail.com (Tool69) Date: 23 Nov 2006 01:36:56 -0800 Subject: Finding the carret position in a regular expression Message-ID: <1164274616.881372.276400@l39g2000cwd.googlegroups.com> Hi, supposed I've got the following text : mytext = "for in :" with the following simple pattern : pattern = "<[a-z]+>" I use re.findall(pattern, mytext) wich returns : ['',''] Now, I want my prog to return the positions of the returned list elements, ie : was found at position 5 in mytext was found at position 16 in mytext How can I implement this ? Sorry if it's trivial, that's the first time I use regular expressions. Thanks, 6Tool9 From mpeters42 at gmail.com Sat Nov 18 12:58:06 2006 From: mpeters42 at gmail.com (Mark Peters) Date: 18 Nov 2006 09:58:06 -0800 Subject: basic python questions In-Reply-To: <1163829271.660193.70450@j44g2000cwa.googlegroups.com> References: <1163829271.660193.70450@j44g2000cwa.googlegroups.com> Message-ID: <1163872686.136760.311450@h54g2000cwb.googlegroups.com> nateastle at gmail.com wrote: > dict = {} As a general rule you should avoid variable names which shadow built in types (list, dict, etc.). This can cause unexpected behavior later on. Also, variable names should be more descriptive of their contents. Try word_dict or some such variant From mailtogops at gmail.com Mon Nov 13 14:12:09 2006 From: mailtogops at gmail.com (mailtogops at gmail.com) Date: 13 Nov 2006 11:12:09 -0800 Subject: HTML Parsing and Indexing Message-ID: <1163445129.232987.110300@e3g2000cwe.googlegroups.com> Hi All, I am involved in one project which tends to collect news information published on selected, known web sites inthe format of HTML, RSS, etc and sortlist them and create a bookmark on our website for the news content(we will use django for web development). Currently this project is under heavy development. I need a help on HTML parser. I can download the web pages from target sites. Then I have to start doing parsing. Since they all html web pages, they will have different styles, tags, it is very hard for me to parse the data. So what we plan is to have one or more rules for each website and run based on rule. We can even write some small amount of code for each web site if required. But Crawler, Parser and Indexer need to run unattended. I don't know how to proceed next.. I saw a couple of python parsers like pyparsing, yappy, yapps, etc but they havn't given any example for HTML parsing. Someone recommended using "lynx" to convert the page into the text and parse the data. That also looks good but still i end of writing a huge chunk of code for each web page. What we need is, One nice parser which should work on HTML/text file (lynx output) and work based on certain rules and return us a result (Am I need magix to do this :-( ) Sorry about my english.. Thanks & Regards, Krish From jm.suresh at gmail.com Mon Nov 13 06:08:05 2006 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 13 Nov 2006 03:08:05 -0800 Subject: Data structure for ordered sequence In-Reply-To: References: <1163410449.081226.49270@i42g2000cwa.googlegroups.com> Message-ID: <1163416085.099968.185390@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: > jm.suresh at no.spam.gmail.com wrote: > > > I am looking for a data structure to hold rectangles in a 2d space. > > Please point me to any module which does these operations: > > Insert a rectangle into a particular co-ordinate. > > Get the rectangle/s right/left/above/below side to a particular > > rectangle. > > Get all the rectangles within a box > > Delete a particular rectangle. > > how many rectangles do you plan to store in this structure? > > Around 150 max Thanks for the response. -- Suresh From martin at v.loewis.de Mon Nov 20 01:55:23 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 20 Nov 2006 07:55:23 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: <1163992410.229236.60830@e3g2000cwe.googlegroups.com> References: <18c54$455d019b$59ad1aca$24364@news.flashnewsgroups.com> <455d507d$0$18480$9b622d9e@news.freenet.de> <3188c$455d923f$59ad1aca$4742@news.flashnewsgroups.com> <455E5D15.7030207@v.loewis.de> <3e540$4560b958$59ad1aca$32456@news.flashnewsgroups.com> <4560E3AE.5030307@v.loewis.de> <1163992410.229236.60830@e3g2000cwe.googlegroups.com> Message-ID: <4561515B.4060106@v.loewis.de> Ross Ridge schrieb: > Martin v. L?wis wrote: >> One approach I had been considering is to always make the decoding >> succeed, by using the private-use-area of Unicode to represent bytes >> that don't decode correctly. > > That would conflict with private use characters appearing in file > names. Not necessarily: they could get escaped. AFAICT, you can have that conflict only if the file system encoding is UTF-8: otherwise, there is no way to represent them. > Personally, I think os.listdir() should return the file names only in > Unicode if they're actually stored that way in the underlying file > system (eg. NTFS), otherwise return them as byte strings. I doubt > anyone in this thread would like that, though. So I assume you would not want to allow to pass Unicode strings to open(), stat() etc. either, as the _real_ file system API requires byte strings there, as well? People would indeed see that as a step backwards. If you don't want Unicode strings returned from listdir, don't pass Unicode string as the directory name. Technically, how do you determine whether the underlying file system stores file names "in Unicode"? Does OSX use Unicode (it requires path names to be UTF-8)? After all, each and every encoding is a Unicode encoding - that was a design goal of Unicode. Regards, Martin From nick-news at net4u.hr Fri Nov 24 13:50:12 2006 From: nick-news at net4u.hr (Nikola Skoric) Date: Fri, 24 Nov 2006 19:50:12 +0100 Subject: cron job times out Message-ID: Hello, I have a few lines of code retrieving a web page and saving some variables from it to a log. And everything works nice from command line. but, when I make a cron job, I get an error: Your "cron" job on fly cd $HOME/bin/ ; python newartlog.py ; cd produced the following output: Traceback (most recent call last): File "newartlog.py", line 11, in ? response = urllib2.urlopen(req) File "/usr/local/lib/python2.4/urllib2.py", line 130, in urlopen return _opener.open(url, data) File "/usr/local/lib/python2.4/urllib2.py", line 358, in open response = self._open(req, data) File "/usr/local/lib/python2.4/urllib2.py", line 376, in _open '_open', req) File "/usr/local/lib/python2.4/urllib2.py", line 337, in _call_chain result = func(*args) File "/usr/local/lib/python2.4/urllib2.py", line 1021, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/local/lib/python2.4/urllib2.py", line 996, in do_open raise URLError(err) urllib2.URLError: It seems that the connection timed out. But, every time I execute the script from the command line, everything goes fine. And every time he cron job triggers, it times out. How come? -- "Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams" From rrr at ronadam.com Mon Nov 13 15:38:08 2006 From: rrr at ronadam.com (Ron Adam) Date: Mon, 13 Nov 2006 14:38:08 -0600 Subject: Py3K idea: why not drop the colon? In-Reply-To: <4558B9E3.2040207@hobbshouse.org> References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <17750.22816.636590.485360@montanaro.dyndns.org> <4558B9E3.2040207@hobbshouse.org> Message-ID: Michael Hobbs wrote: > Ron Adam wrote: >> skip at pobox.com wrote: >> >>> >>>>> I'm not sure why '\'s are required to do multi-line before the colon. >>> >>>> Special cases aren't special enough to break the rules. >>> >>>> >>> >>>> Georg >>> >>> A bit of a circular answer. >>> >>> >>> >>> Why the rule? -> So not to break the rule? >>> >> >>> >> You proposed to allow leaving off line continuation '\' only in the >>> >> "if", "for" and "while" headers. This is a special case in my eyes. >>> >>> Ron> I wasn't that specific and it was related to Michael's suggestion >>> Ron> the colon wasn't needed. If the need for '\' was dropped in >>> Ron> multi-line block headers, then the colon would be required for an >>> Ron> obvious reason. >>> >>> But \ is used to continue all sorts of statements/expressions, e.g.: >>> >>> x = a + \ >>> b >>> >>> not just conditionals. >>> >>> Skip >>> >> Of course, and your point is? >> >> How about if it be ok to continue to use '\' in headers, but it also be ok to >> not to? That would be the backward compatible way to change it. >> >> This doesn't answer the question I was asking, are there any situation where it >> would cause problems? And if so, that reason would be a good and explicit >> reason for not making such a change > > To be clear, this is the actual thrust of my argument. It seems > redundant to have *both* line continuations and colons in compound > statements. I've been arguing for the removal of colons, though to be > honest, I'd be content with the opposite approach as well. > > - Mike Well, maybe you should consider working on that instead. I think you will get much less resistance. Consider the following points: * There are not (that I know of) any true multiple line block headers in python but only long block headers with continued lines. * It's probably more beneficial to simplify the more complex cases of multiple continued lines, than it is to simplify the already simple cases of non continued block headers. * The block header can be identified in all cases by the initiating keyword and the terminating colon. (colons in lambda and dicts need to be identified first) * The block header can not always be clearly identified strictly based on indenting as indenting in a block header spanning several lines is completely optional and may vary quite a bit depending on the programmers preferences. * Line continuations are *already* currently optional in other situations. >>> a = (1, ... 1, ... 3, ... 4, ... 5) >>> a (1, 1, 3, 4, 5) >>> b = (6, \ ... 7, \ ... 8, \ ... 9) >>> b (6, 7, 8, 9) * Making line continuations optional requires no changes to the existing library. * Removing colons would require changing block headers for all existing programs and pythons library unless you made the ending colon optional. But that probably would create more confusion and hurt readability more than it improves it. So giving these points, and any others you can think of, which do you suppose has a better chance of being implemented? It also needs to be pointed out that the line continuations are a strong visual indication that a line is continued and not just a aid to the compiler. So there will be resistance to changing that also. (Over and above the general resistance to change most people have.) Cheers, Ron From skip at pobox.com Sun Nov 12 17:47:59 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 12 Nov 2006 16:47:59 -0600 Subject: Random image text generation? In-Reply-To: References: Message-ID: <17751.42143.36842.842728@montanaro.dyndns.org> Steven> Keep in mind two serious problems with captchas: Steven> - they're impossible for the blind or people using text-only Steven> browsers to see -- even mere colour blindness can make some Steven> captchas impossible to solve; Steven> - sometimes they're too difficult for even those with perfect Steven> vision to decipher. Sure, but I'm more concerned in the immediate term with people not submitting random crap advertising cheap drugs into my concert database. (I've been running the Musi-Cal concert database for nearly 12 years. This is the first time I've ever had to consider resorting to something like this, and it really pisses me off that I have to.) I can deal with visual impairment in other ways (like asking users who can't respond to the captcha by simply emailing their concert data directly to me). Steven> Instead of displaying an obfuscated image of a nonsense word, ... Thanks for the suggestions. I'll keep them in mind. Another possibility is to run the submissions through SpamBayes and silently direct any which score as "unsure" or "spam" to me for review. Users wouldn't even need to know their submissions were being scrutinized. Skip From saleem.a.ansari at gmail.com Sun Nov 26 11:46:50 2006 From: saleem.a.ansari at gmail.com (parser) Date: 26 Nov 2006 08:46:50 -0800 Subject: ANN: RuPy Ruby & Python Conference 2007 In-Reply-To: <1164558164.421675.302290@14g2000cws.googlegroups.com> References: <1164558164.421675.302290@14g2000cws.googlegroups.com> Message-ID: <1164559610.340858.170920@l12g2000cwl.googlegroups.com> This is a really great news for both Ruby and Python lovers!! Katarzyna Bylec wrote: > Hello, > > we would like to invite you to one of the biggest Ruby and Python > events in > central-eastern Europe next year. RuPy Conference dedicated to Ruby and > Python programming languages will take place in April 14-15, 2007 in > Poznan, > Poland and the idea behind it is to put together experts with young > programmers and to support a good communication channel for East-West > exchange of prospective ideas. > > If you think you have something interesting to present or some ideas to > > share with other enthusiasts, we would be more then happy to welcome > you as > a Speaker. Proposals of lectures (i.e. title and short abstract) can be > submitted to rupy-talks at wmid.amu.edu.pl . > > Speakers' registration includes attendance at lecture sessions on both > days > of the Conference, all refreshments during the coffee breaks and > Conference > lunches. For each participant Organizers guarantee free accommodation > and > full board during the Conference. As a Speaker you will also be > entitled to > partial reimbursement for the travel expenses.You are also more than > welcome > to participate in all extra events including guided sightseeing, > conference > Banquet and other entertainments provided by Organizers. > > All information can be found on RuPy website: > http://rupy.wmid.amu.edu.pl > > Looking forward to seeing you in Poland, > RuPy Committee From tdgrmsn at gmail.com Wed Nov 22 21:30:20 2006 From: tdgrmsn at gmail.com (ToddG) Date: 22 Nov 2006 18:30:20 -0800 Subject: Python, WSGI, legacy web application In-Reply-To: <1164241791.372210.103330@b28g2000cwb.googlegroups.com> References: <1164241791.372210.103330@b28g2000cwb.googlegroups.com> Message-ID: <1164249020.575863.28770@l12g2000cwl.googlegroups.com> > Ben Finney wrote: > > > > Is it possible to write a Python WSGI program that talks to a PHP > > program as its "back end"? Where can I find out how to do this, > > preferably with examples? Perhaps: http://pythonpaste.org/wphp/ http://blog.ianbicking.org/2006-wphp.html From gilbert3b2g at msn.com Wed Nov 15 23:20:25 2006 From: gilbert3b2g at msn.com (gilbert3b2g at msn.com) Date: 15 Nov 2006 20:20:25 -0800 Subject: Press button to load data Message-ID: <1163650825.563379.38550@b28g2000cwb.googlegroups.com> I'm new to Python, and programming in general. What I'm trying to do here is to load a list of accounts from a file on my harddrive into a string of Buttons in Tkinter, and when I press one of the Buttons, which has one of my account name, it will load that account into a new window. But I don't understand how to code the proccess that would tell the program what account is selected. Any help with this would be very appreciated. Thanks in advance. from Tkinter import * import shelve from tkMessageBox import showerror shelvename = shelve.open('class-shelve2') cat = (' Name ', ' Account # ', ' Amount Due ', ' Date Due ') def NameFields(top): name1 = Label(None, text=cat[0], relief=RIDGE, width=20, fg='blue', bg='white', font=('bold',15)) name2 = Label(None, text=cat[1], relief=RIDGE, width=15, fg='blue', bg='white', font=('bold',15)) name3 = Label(None, text=cat[2], relief=RIDGE, width=15, fg='blue', bg='white', font=('bold',15)) name4 = Label(None, text=cat[3], relief=RIDGE, width=15, fg='blue', bg='white', font=('bold',15)) name1.grid(row=0, column=0, sticky=NSEW) name2.grid(row=0, column=1, sticky=NSEW) name3.grid(row=0, column=2, sticky=NSEW) name4.grid(row=0, column=3, sticky=NSEW) top.columnconfigure(0, weight=1) top.columnconfigure(1, weight=1) top.columnconfigure(2, weight=1) top.columnconfigure(3, weight=1) def DisplayBills(top): c=0 for bill in shelvename: bill1 = Button(None, text= shelvename[bill].name, font=('bold',10), command=fetchRecord) bill2 = Label(None, text= shelvename[bill].account, relief=RIDGE, font=('bold',10)) bill3 = Label(None, text= shelvename[bill].paymentDue, relief=RIDGE, font=('bold',10), fg='red') bill4 = Label(None, text= shelvename[bill].dateDue, relief=RIDGE, font=('bold',10)) bill1.grid(row=c, column=0, sticky=NSEW) bill2.grid(row=c,column=1, sticky=NSEW) bill3.grid(row=c,column=2, sticky=NSEW) bill4.grid(row=c,column=3, sticky=NSEW) c = c + 1 def fetchRecord(): top = Tk() DisplayBills(top), NameFields(top) mainloop() From Roberto.Bonvallet at cern.ch Wed Nov 29 10:35:37 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Wed, 29 Nov 2006 15:35:37 +0000 (UTC) Subject: trouble writing results to files References: <1164812827.653386.323320@80g2000cwy.googlegroups.com> Message-ID: Neil Cerutti wrote: > On 2006-11-29, Roberto Bonvallet wrote: >> BTW, iterating over range(len(a)) is an anti-pattern in Python. > > Unless you're modifying elements of a, surely? enumerate is your friend :) for n, item in enumerate(a): if f(item): a[n] = whatever -- Roberto Bonvallet From B.Ogryczak at gmail.com Wed Nov 29 13:26:30 2006 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 29 Nov 2006 10:26:30 -0800 Subject: pickle and infinity In-Reply-To: References: <1164820161.480995.180500@l12g2000cwl.googlegroups.com> Message-ID: <1164824790.211227.305300@14g2000cws.googlegroups.com> Fredrik Lundh wrote: > Bart Ogryczak wrote: > > > I?ve got this problem with pickle, it seems it doesn?t handle > > correctly infinite values (nor does Python return overflow/underflow > > error). > > Python 2.X relies on the C library to serialize floats, and, as you've > noticed, some C libraries can produce values that they themselves cannot > read. Actually I?d be very happy, if Python would throw FloatPointExeption, rather then allow infinite values. Haven?t got idea how to do it. fpectl would do the trick, but it?s not present nither on Solaris, nor on Windows platform. And I?d need it on both. From apardon at forel.vub.ac.be Fri Nov 17 10:21:33 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Nov 2006 15:21:33 GMT Subject: How fuzzy is get_close_matches() in difflib? References: <1163724049.225348.118020@h54g2000cwb.googlegroups.com> <1163737190.118975.227740@h48g2000cwc.googlegroups.com> <1163746781.666937.63970@h48g2000cwc.googlegroups.com> Message-ID: On 2006-11-17, John Henry wrote: > I encountered a case where I am trying to match "HIDESST1" and > "HIDESCT1" against ["HIDEDST1", "HIDEDCT1", "HIDEDCT2", "HIDEDCT3"] > > Well, they both hit "HIDEDST1" as the first match which is not exactly > the result I was looking for. I don't understand why "HIDESCT1" would > not hit "HIDEDCT1" as a first choice. H I D E D S T 1 H I D E D C T 1 H . . I . . D . . E . . S . C . T . . 1 . . As far as I can see the distance of HIDEDCT1 to HIDESCT1 is the same as the distance of HIDEDCT1 to HIDEDST1. In both cases you have to remove one character from the target as well as one character from the candidate in order to get the same substring. -- Antoon Pardon From ptmcg at austin.rr._bogus_.com Sun Nov 26 06:54:49 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 26 Nov 2006 11:54:49 GMT Subject: a -very- case sensitive search References: <1164490795.866046.133230@45g2000cws.googlegroups.com> <1164541566.246893.279680@l12g2000cwl.googlegroups.com> Message-ID: "John Machin" wrote in message news:1164541566.246893.279680 at l12g2000cwl.googlegroups.com... > John - Thanks for the updates. Comments below... -- Paul > Paul McGuire wrote: > >> You may have to do some setup >> of your locale for proper handling of unicode.isupper, etc., > > Whatever gave you that impression? > Nothing. Just my own ignorance of unicode and i18n. This post really is just string mechanics and re's - I wasn't sure I had all the underlying unicode stuff right. >> uppers = u"".join( unichr(i) for i in range(sys.maxunicode) >> if unichr(i).isupper() ) >> lowers = u"".join( unichr(i) for i in range(sys.maxunicode) >> if unichr(i).islower() ) > > Just in case the OP is running a 32-bit unicode implementation, you > might want to make that xrange, not range :-) > Good tip. I rarely use xrange, it seems like such a language wart. Isn't "range" going to become what "xrange" is in Py3k? From johnjsal at gmail.com Thu Nov 2 15:29:17 2006 From: johnjsal at gmail.com (JohnJSal) Date: 2 Nov 2006 12:29:17 -0800 Subject: what's the difference between these two methods? (aka, why doesn't one of them work?) In-Reply-To: <1162499293.080529.5480@m73g2000cwd.googlegroups.com> References: <1162499293.080529.5480@m73g2000cwd.googlegroups.com> Message-ID: <1162499357.481355.293910@b28g2000cwb.googlegroups.com> JohnJSal wrote: > Can someone explain to me why the first version of this method works, > but the second one doesn't? Sorry, it's the first one that doesn't work. The second one does. From bj_666 at gmx.net Thu Nov 30 08:47:48 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 30 Nov 2006 14:47:48 +0100 Subject: PythonTidy References: Message-ID: In , Laurent Pointal wrote: > Roberto Bonvallet a ?crit : >> # vim: set fileencoding=utf-8 : > ... >> # -*- coding: utf-8 -*- > ... >> About changing the shebang line: I'll take it as a bug. >> About changing the encoding declaration from vim-style to emacs-style: >> I'll take it as an insult :) > > This is not "emacs-style", this is Python normalized source encoding > directive for correct interpretation of u"..." strings by Python > interpreter. > > See http://www.python.org/dev/peps/pep-0263/ Where does it say it has to be emacs-style? It just uses that style as example as far as I can see. The real definition is a regexp: coding[:=]\s*([-\w.]+) So the vim-style is fine. No need to replace it. Ciao, Marc 'BlackJack' Rintsch From ndbecker2 at gmail.com Sun Nov 12 07:01:24 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Sun, 12 Nov 2006 07:01:24 -0500 Subject: Find interface associated with default route? References: Message-ID: Fredrik Lundh wrote: > Neal Becker wrote: > >> Any thoughts on howto find the interface associated with the default >> route (this is on linux)? > > are you sure you sent this to the right newsgroup ? > > is this what you want ? > > >>> import os > >>> for line in os.popen("/sbin/route"): > ... line = line.split() > ... if line[0] == "default": > ... print line[-1] > ... > eth0 > Well, I was hoping for something more 'elegant' - meaning relying on library calls rather than calling programs. Obviously, /sbin/route has some library calls to obtain this info, and maybe python has a wrapper for it. Yes, this is the right group - I want a python solution. From martin at v.loewis.de Wed Nov 8 00:10:14 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 08 Nov 2006 06:10:14 +0100 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? In-Reply-To: <1162939715.915139.146890@b28g2000cwb.googlegroups.com> References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <7xk62ct5pf.fsf@ruckus.brouhaha.com> <1162913881.953664.254960@m73g2000cwd.googlegroups.com> <1162922230.992249.52430@f16g2000cwb.googlegroups.com> <4550cc64$0$3462$9b622d9e@news.freenet.de> <1162928970.223276.72600@h48g2000cwc.googlegroups.com> <4550F2AE.1010205@v.loewis.de> <1162939715.915139.146890@b28g2000cwb.googlegroups.com> Message-ID: <455166B6.6040009@v.loewis.de> Ross Ridge schrieb: > So give an example where reference counting is unsafe. Nobody claimed that, in that thread. Instead, the claim was "Atomic increment and decrement instructions are not by themselves sufficient to make reference counting safe." I did give an example, in <4550cc64$0$3462$9b622d9e at news.freenet.de>. Even though f_name is reference-counted, it might happen that you get a dangling pointer. More specifically, even if file_repr *incremented* the reference counter for f_name, it might still be a dangling pointer. To quote Joe again: # Basically there's a race condition where an object containing the # refcount can be deleted between the time you load a pointer to # the object and the time you increment what used to be a refcount # and is possibly something else but definitely undefined. I don't understand why you can't see that this statement is factually correct. Regards, Martin From jonas.esp at googlemail.com Thu Nov 23 18:41:13 2006 From: jonas.esp at googlemail.com (GinTon) Date: 23 Nov 2006 15:41:13 -0800 Subject: sys.stderr.write and sys.exit In-Reply-To: References: <1164278785.075748.220690@j44g2000cwa.googlegroups.com> Message-ID: <1164325273.510305.121230@m7g2000cwm.googlegroups.com> Thanks Ben Finney. So it's understood very well. Ben Finney ha escrito: > "GinTon" writes: > > > Is the same use >> >>> sys.stderr.write('error message'); sys.exit(1) > > than >> >>> sys.exit('error message') ? > > Code that wants to catch SystemExit will get a different exception > object in each case:: > > >>> import sys > >>> from StringIO import StringIO > >>> sys.stderr = StringIO() > > >>> try: > ... sys.stderr.write('error message') > ... sys.exit(1) > ... except SystemExit, e: > ... print "stderr contains:", sys.stderr.getvalue() > ... print "e.code is:", e.code > ... > stderr contains: error message > e.code is: 1 > > >>> try: > ... sys.exit('error message') > ... except SystemExit, e: > ... print "stderr contains:", sys.stderr.getvalue() > ... print "e.code is:", e.code > ... > stderr contains: error message > e.code is: error message > > I quite often catch SystemExit in unit tests, or other code that is > inspecting a program module. From fredrik at pythonware.com Fri Nov 17 07:25:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 17 Nov 2006 13:25:33 +0100 Subject: What python modules are available? In-Reply-To: <1163765733.745577.116670@m73g2000cwd.googlegroups.com> References: <1163765733.745577.116670@m73g2000cwd.googlegroups.com> Message-ID: Why Tea wrote: > How do I find out what python modules are installed on a Solaris > platform? ask the person who did the installation? or run this script: http://svn.effbot.python-hosting.com/pydotorg/listmodules/listmodules.py > I tried to import numarray, but python couldn't find it. numarray isn't a standard module; see the library reference for a list of modules that you can expect to be available on most platforms (but make sure you check the page for the modules you're interested in, to see if they're platform-specific or otherwise optional) From tony.ha at philips.com Wed Nov 15 10:56:41 2006 From: tony.ha at philips.com (tony.ha at philips.com) Date: Wed, 15 Nov 2006 15:56:41 GMT Subject: How to pass an argument to a python program open in IDLE? Message-ID: Hello, I have open a Python program in the IDLE, but when I select the "run module" under "run" menu, it does not allow me to pass an argument to my Python program! How do you pass an argument to a Python program under the IDLE? Thanks for you help! -------------- next part -------------- An HTML attachment was scrubbed... URL: From userprogoogle-139 at yahoo.co.uk Mon Nov 13 11:15:28 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 13 Nov 2006 08:15:28 -0800 Subject: CORBA: Fnorb Problems References: <1163430997.532317.206850@b28g2000cwb.googlegroups.com> <4rrj89FspqicU1@mid.uni-berlin.de> Message-ID: <1163434528.147036.63610@f16g2000cwb.googlegroups.com> > > I used omniorb, and have been very satisfied with it. You might consider > switching. > > Diez Thanks, I have just downloaded that plus omniORBpy as well. I have the binary version of omniORB but need to build omniORBpy, from what I can see the build process is aimed at GCC and not VC++. Anyway I will try to figure it out. Best, rod From steve at REMOVE.THIS.cybersource.com.au Thu Nov 9 08:33:10 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 10 Nov 2006 00:33:10 +1100 Subject: substring search without using built in utils References: <45530805$0$10013$426a74cc@news.free.fr> <1163071862.056378.13870@f16g2000cwb.googlegroups.com> Message-ID: On Thu, 09 Nov 2006 03:31:02 -0800, John Machin wrote: > > Bruno Desthuilliers wrote: >> Gabriel Genellina wrote: >> > At Wednesday 8/11/2006 22:29, zeal elite wrote: >> > >> >> I am looking for substring search python program without using the >> >> built in funtions like find, or 'in'. >> > >> > The only reasonable usage for such a constraint would be a school >> > assignment so: don't cheat and do your homework! >> > >> >> OTHO, looking for existing solutions to a same or similar problem and >> studying them is usually considerer good practice in real-life >> programming jobs !-) >> > > Looking at an existing solution for substring search that was coded in > Python, instead of using the built-in functionality would IMHO be > considered extremely bad practice in a real-life programming job. Sure. But what if the data type in question wasn't a string, but a list? Given a source list, find the offset of a target sub-list within the source list, in other words, find for lists. i.e. search(source, target) returns n if source[n:n+len(target)] == target for any sequence type. Yes, I know I'm changing the constraints of the problem. Now for a real challenge, change the search from a one-dimensional data structure to two. (The solution is left as an exercise for the class.) -- Steve. From bn.sharath at gmail.com Fri Nov 17 02:22:23 2006 From: bn.sharath at gmail.com (sharath B N) Date: Fri, 17 Nov 2006 12:52:23 +0530 Subject: problem with defining a global class instance Message-ID: hi, i am sort of newbie to python. I am trying to do a super Market simulation with OOP in python. I have problems with using a class instance as global... def generate (... ,....,...) " in this function i define the global variables " global stock,stockManager, manager etc. class Manager ... ... ... def create_stockManager(..) """ this is a method in class manager""" stockManager = StockManager( name) stockManager.create_Stock(..) now this gives an attribute error sayin .... stockManager has no attribute create_Stock if i create the StockManager instance in the generate func itself...then this problem doesnt come....but i need it this way for the program to make sense.. can somebody help me thnks Sharath From kay.schluehr at gmx.net Tue Nov 21 09:22:35 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 21 Nov 2006 06:22:35 -0800 Subject: Reference class in class creation References: <4sga7nFsi0j0U1@mid.uni-berlin.de> <7ebdb$456303ba$547078de$26211@news.chello.at> Message-ID: <1164118954.982140.225980@m7g2000cwm.googlegroups.com> Is there a reason why don't you drop the metaclass and perform the validation step after the class has been created using a generic function? class Tour(MotourController): pass Tour.sqlobjectclass = model.Tour Tour.widget_edit = TourEdit(controller=Tour, name = "tourheader", ...) Tour = validate(Tour) From sjmachin at lexicon.net Thu Nov 9 18:44:00 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Nov 2006 15:44:00 -0800 Subject: pack a three byte int In-Reply-To: <1163114202.636000.234900@m73g2000cwd.googlegroups.com> References: <1163027401.386603.263030@k70g2000cwa.googlegroups.com> <1163092047.577688.140400@m73g2000cwd.googlegroups.com> <1163114202.636000.234900@m73g2000cwd.googlegroups.com> Message-ID: <1163115840.190634.5800@m73g2000cwd.googlegroups.com> p.lavarre at ieee.org wrote: > > Not as concisely as a one-byte struct code > > Help, what do you mean? Help, what did you mean by the question? "struct" == "Python struct module" Struct module has (concise) codes B, H, I, Q for unsigned integers of lengths 1, 2, 4, 8, but does *not* have a code for 3-byte integers. > > > you presumably... read... the manual ... > > Did I reread the wrong parts? I see I could define a ctypes.Structure > since 2.5, but that would be neither concise, nor since 2.3. Looks like you ignored the first word in the sentence ("Not"). > > > when 24-bit machines become ... popular > > Indeed the struct's defined recently, ~1980, were contorted to make > them easy to say in C, which makes them easy to say in Python, e.g.: > > X28Read10 = 0x28 > cdb = struct.pack('>BBIBHB', X28Read10, 0, skip, 0, count, 0) > > But when talking the 1960's lingo I find I am actually resorting to > horrors like: > > X12Inquiry = 0x12 > xxs = [0] * 6 > xxs[0] = X12Inquiry > xxs[4] = allocationLength > rq = ''.join([chr(xx) for xx in xxs]) > > Surely this is wrong? A failure on my part to think in Python? It looks wrong (and a few other adjectives), irrespective of what problem it is trying to solve. Looks like little-endian 4-byte integer followed by 2-byte integer ... what's wrong with struct.pack(" References: <1164039347.784574.294770@h54g2000cwb.googlegroups.com> Message-ID: <1164082463.650146.315230@k70g2000cwa.googlegroups.com> it works with base64 thanks alot!!!, I know it's not very good solution, but it's for a multiplayer checkers game with webcam, and I already use enet everywhere Fredrik Lundh a ?crit : > maxime_phan at hotmail.com wrote: > > > Hello everyone, I'm trying to make a webcam software with python, pil > > library and enet (networking) > > Now I have in the client my pil image get from webcam, ready to be send > > by network. > > > > I do that: > > > > self.peer.send(0, image.tostring(), enet.FLAG_RELIABLE) > > > > and I have this error: > > TypeError: argument 2 must be string without null bytes, not str > > > > does someone know what kind of convertion I should do to make it work? > > "self.peer", whatever that is, doesn't seem to support transfer > of binary data. better talk to the vendor. > > (you could in theory use base64 encoding or some other text-only > representation of binary data, but that doesn't seem like a very > practical solution for a webcam application.) > > From gagsl-py at yahoo.com.ar Wed Nov 29 05:45:42 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 29 Nov 2006 07:45:42 -0300 Subject: Asyncore Medusa Example In-Reply-To: <456D5FBA.2010909@contrado.com.au> References: <456D5FBA.2010909@contrado.com.au> Message-ID: <7.0.1.0.0.20061129074123.053c09c0@yahoo.com.ar> At Wednesday 29/11/2006 07:23, Graeme Matthew wrote: >does anyone know where you can find examples of how to write a native >python webserver, I have looked at medusa and asyncore but there are no >real examples and the doco is very light The Python standard library already comes with a native HTTP server. And you have menctioned Medusa, and there is also Twisted and... try google to find more examples. Do you want to write *another* one? -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From sjmachin at lexicon.net Tue Nov 21 14:23:12 2006 From: sjmachin at lexicon.net (John Machin) Date: 21 Nov 2006 11:23:12 -0800 Subject: Parsing/Splitting Line In-Reply-To: References: <1164088789.316244.124340@b28g2000cwb.googlegroups.com> Message-ID: <1164136992.636009.251950@k70g2000cwa.googlegroups.com> Neil Cerutti wrote: > On 2006-11-21, acatejr at gmail.com wrote: > > I have a text file and each line is a list of values. The > > values are not delimited, but every four characters is a value. > > How do I get python to split this kind of data? Thanks. > > Check out _Text Processing in Python_, Chapter 2, "PROBLEM: > Column statistics for delimited or flat-record files". > URL:http://gnosis.cx/TPiP/ Hmmmm ... the elementary notion "do line[start:end] in a loop" is well buried, just behind this: # Adjust offsets to Python zero-based indexing, # and also add final position after the line num_positions = len(self.column_positions) offsets = [(pos-1) for pos in self.column_positions] offsets.append(len(line)) Folk who are burdened with real-world flat files (example: several hundred thousand lines each of 996 bytes wide) might want to consider moving the set-up of "offsets" out of the once-per line splitter() method to the __init__() method :-) Cheers, John From noone at nowhere.com Sun Nov 5 14:26:38 2006 From: noone at nowhere.com (avidfan) Date: Sun, 05 Nov 2006 13:26:38 -0600 Subject: question about loading variables from a file... Message-ID: Can someone offer some advice as to how the best way to approach this might be? I am trying to write a generic python script to build out some applications, so the python script will be generic enough to work for all of them, but it needs to 'source' a file that contains app and environment specific variables. I have used WLST, which provides the loadProperties() method for reading values for weblogic domains, but I'm trying to find the best way to do the same sort of thing in python... thanks for any advice. From orsenthil at gmail.com Mon Nov 13 08:07:38 2006 From: orsenthil at gmail.com (Phoe6) Date: 13 Nov 2006 05:07:38 -0800 Subject: httplib.InvalidURL: nonnumeric port: For characters in the proxypassword in URL In-Reply-To: References: <1163408210.915911.327430@k70g2000cwa.googlegroups.com> <1163419232.632721.192360@i42g2000cwa.googlegroups.com> Message-ID: <1163423258.919153.281260@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: Hi Fredrik, I apologize if I offended you or have shown any impatience. I shall try again: > oh, please. urllib.quote is a *function*; there's no way that calling that function > from code written for urllib2 will affect anything. > > but you can access urllib.quote from the urllib2 namespace too. it's actually the > very same function: > > >>> urllib.quote > > >>> urllib2.quote > > > (urllib2 imports lots of stuff from urllib) I dont know, it does not for me. >>> urladd = "http://example.net:80 at username:|\/|pr0c" >>> print urladd http://example.net:80 at username:|\/|pr0c >>>import urllib2 >>> url = urllib2.quote(urladd) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'quote' >>> import urllib >>> url = urllib.quote(urladd) >>> print url http%3A//example.net%3A80%40username%3A%7C%5C/%7Cpr0c >>> > > I dont want to import urllib, with the urllib2 itself wanted to work > > around this piece of code. > > not wanting to solve a problem is a pretty lousy problem-solving strategy, really. Sorry. :-) I shall take your advice and try to get to bottom of this issue. - To the piece of code, I import urllib - use urllib.quote() to covert the proxy url to a quoted one. and try again, I get an error: Traceback (most recent call last): File "C:\Python24\forge\ngwallp\ngwall.py", line 38, in ? data = urllib2.urlopen(site) File "C:\Python24\lib\urllib2.py", line 130, in urlopen http://lava.nationalgeographic.com/cgi-bin/pod/wallpaper.cgi?day=13&month=11&year=06 return _opener.open(url, data) File "C:\Python24\lib\urllib2.py", line 358, in open response = self._open(req, data) File "C:\Python24\lib\urllib2.py", line 376, in _open '_open', req) File "C:\Python24\lib\urllib2.py", line 337, in _call_chain result = func(*args) File "C:\Python24\lib\urllib2.py", line 573, in lambda r, proxy=url, type=type, meth=self.proxy_open: \ File "C:\Python24\lib\urllib2.py", line 580, in proxy_open if '@' in host: TypeError: iterable argument required This is where, I gave up and wrote the previous email as not to mess up urllib with urllib2. The piece of code, was working properly till I changed my proxy password to something containng '|\/|'. - Before shooting a mail to the grooups, i kindda encoded password to valid url characters ( %7C%5C/%7C) and tried. But this did not work. So, I dont think this is urllib.quote() issue. I am looking for a way as how to use the ProxyHandler with authentication in different way than I have used below. proxy_url_add = r'http://' + proxy_user + ':' + proxy_password + '@' + PROXY_IP proxy_url = urllib.quote(proxy_url_add) proxy_support = urllib2.ProxyHandler({"http":proxy_url}) opener = urllib2.build_opener(proxy_support,urllib2.HTTPHandler) urllib2.install_opener(opener) Thanks for your response. Regards, Senthil From sjmachin at lexicon.net Sat Nov 25 21:03:13 2006 From: sjmachin at lexicon.net (John Machin) Date: 25 Nov 2006 18:03:13 -0800 Subject: a -very- case sensitive search In-Reply-To: <1164496061.281428.126670@l12g2000cwl.googlegroups.com> References: <1164490795.866046.133230@45g2000cws.googlegroups.com> <1164495824.540112.117410@l12g2000cwl.googlegroups.com> <1164496061.281428.126670@l12g2000cwl.googlegroups.com> Message-ID: <1164506593.625847.162830@14g2000cws.googlegroups.com> Dustan wrote: > > If you're using google groups, it for some reason thought my example > code was 'quoted text', which it certainly isn't, seeing as it's not > found anywhere prior to my message. Sigh. And if we're NOT using Google Groups, it still thinks so ... The reason is that your "example code" was in fact a screen-dump of a Python interactive session, in which lines are preceded by ">>>" which Google Groups simplistically thinks is quoted text from a previous message. HTH, John From steve at ferg.org Fri Nov 24 13:30:16 2006 From: steve at ferg.org (Steve) Date: 24 Nov 2006 10:30:16 -0800 Subject: How do I access a main frunction from an import module? References: <1164377547.562483.152770@l12g2000cwl.googlegroups.com> Message-ID: <1164393016.664066.237570@l39g2000cwd.googlegroups.com> This is an interesting question. It almost looks like a case of event-driven programming, where main is the plug-in and abc is the framework. http://eventdrivenpgm.sourceforge.net/ So how about something like this: ################## abc.py #################### #------------------------------------------------------------ # an "abstract" function. # It should be over-ridden in the calling program #------------------------------------------------------------ def m(): raise AssertionError("You should have over-ridden abstract function m()") def a(): m() return None ########### main.py #################### import abc # "instantiate" the framework # define our our "concrete" function m def m(): print 'something' return None #----------------------------------------------- # override the "abstract" function abc.m() # with our own "concrete" function m(). # Comment out this line and see what happens. #----------------------------------------------- abc.m = m # invoke the a() function in the abc framework abc.a() ################################################# From tom at t0mb.net Sat Nov 18 08:58:51 2006 From: tom at t0mb.net (tom) Date: Sat, 18 Nov 2006 13:58:51 +0000 Subject: Having trouble converting popen2 to subprocess In-Reply-To: References: Message-ID: <455F119B.2060805@t0mb.net> Daniel Klein wrote: > Here's a c routine that prints a single line : > > #include > main() > { > printf ("Hello World!\n"); > } > > And now the Python program (called 'po.py') that uses 'popen2' : > > import popen2 > (fin, fout) = popen2.popen2(r'c:\home\hw.exe', -1, 't') > print fin.readline() > fin.close() > fout.close() > > When this is run it properly outputs the one line from the c routine : > > C:\>python c:\python\po.py > Hello World! > > Now here is my attempt to use the 'subprocess' module : > > from subprocess import * > p = Popen(r'c:\home\hw.exe', bufsize=-1, stdin=PIPE, stdout=PIPE, > universal_newlines=True) > fin = p.stdin > print fin.readline() > fin.close() > > When this is run, I get no output : > > C:\>python c:\python\sp.py > > > C:\> > > As you can see, I get no exception. > > I've tried various combinations of the Popen arguments with no joy. > > The platform is Windows XP Pro, so I did not try things like > 'close_fds'. > > What am I missing ? > > Daniel Klein > subprocess will actually execute as a subprocess, so you have to wait for the command to finish before you look at the stdout. Advantages of this being that you can interfere with stdin/out whilst the program is running. I believe .wait will be what you want, although i haven't look at the docstring, so double check. From nnorwitz at gmail.com Sat Nov 18 17:46:26 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 18 Nov 2006 14:46:26 -0800 Subject: How can I speed this function up? In-Reply-To: References: Message-ID: <1163889985.991519.160250@h54g2000cwb.googlegroups.com> Peter Otten wrote: > > # Norvitz/Lundh > def writelines_data(out, data, map=map, str=str): > SPACE_JOIN = ' '.join > out.writelines( > "ELEMENT %06d %s\n" % (i1, SPACE_JOIN(map(str, i2))) > for i0, i1, i2 in data if i0 == 'ELEMENT' > ) > > def print_data(out, data): > for name, index, items in data: > if name == "ELEMENT": > print >> out, "ELEMENT %06d" % index, > for item in items: > print >> out, item, > print >> out > > Output on my machine: > > $ python2.5 writedata.py > write_data 10.3382301331 > writelines_data 5.4960360527 > print_data 3.50765490532 Interesting. I timed with python2.4 and get this: write_data 12.3158090115 writelines_data 5.02135300636 print_data 5.01881980896 A second run yielded: write_data 11.5980260372 writelines_data 4.8575668335 print_data 4.84622001648 I'm surprised by your numbers a bit because I would expect string ops to be faster in 2.5 than in 2.4 thanks to /F. I don't remember other changes that would cause such an improvement for print between 2.4 and 2.5. (2.3 shows print doing a bit better than the times above.) It could be that the variability is high due to lots of I/O or even different builds. I'm on Linux. > Moral: don't forget about good old print. It does have an opcode(*) of its > own, after all. Using print really should be faster as less objects are created. > (*) or two or 5 :-) $ grep 'case PRINT_' Python/ceval.c case PRINT_EXPR: case PRINT_ITEM_TO: case PRINT_ITEM: case PRINT_NEWLINE_TO: case PRINT_NEWLINE: n From rpdooling at gmail.com Fri Nov 24 10:09:36 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 24 Nov 2006 07:09:36 -0800 Subject: Active State and Komodo... In-Reply-To: References: Message-ID: <1164380976.218515.107780@m7g2000cwm.googlegroups.com> Steve Thompson wrote: > > I was wondering the differnced there were betwee Active State's python and > the open source version of python. The biggest difference at the moment is that ActiveState is still using Python 2.4.3 in their distribution. They should be coming out with 2.5 soon. Sounds like you are running Suse? So you already have some version of Python, right? You can search this group at comp.lang.python on Google Groups--try "python versions linux"--or something like that--but the issue you need to watch out for is running two different versions on Linux. Long and short, you don't want to uninstall the version of Python that came with your Suse, because other programs on your machine probably use that particular version. It's easy to install an ADDITIONAL distribution of Python and run it separately, but again. Search the list for how to do that, and how to run them separately once you do. I'm just moving to Linux myself, so can't provide the expertise. Unless there is some killer feature of 2.5 you need, I would just use the Python that came with your Suse. rd From inq1ltd at verizon.net Wed Nov 29 23:55:51 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Wed, 29 Nov 2006 23:55:51 -0500 Subject: odict the Ordered Diction 0.2.2 In-Reply-To: <1164811281.405346.227240@l12g2000cwl.googlegroups.com> References: <1164811281.405346.227240@l12g2000cwl.googlegroups.com> Message-ID: <200611292355.51786.inq1ltd@verizon.net> Thanks for the post, Its become a part time job keeping up with updates. jim-on-linux http://www.inqvista.com On Wednesday 29 November 2006 09:41, Fuzzyman wrote: > After a break of almost a year there has been > an update to `odict the Ordered Dictionary > >`_. > > The latest version is 0.2.2, with changes > implemented by Nicola Larosa. > > Despite over 700 downloads since May (plus 1300 > as part of `pythonutils > .html>`_) there have been no bug reports, only > improvements [#]_. {sm;:-)} > > * `Quick Download > downman.py?file=odict.py>`_ > > What is odict? > ========== > > **odict** is a pure Python implementation of an > ordered dictionary. It keeps keys in insertion > order and allows you to change the order. > Methods (including iteration) that would return > members in an arbitrary order are now ordered. > > There is also the `SequenceOrderedDict > sequenceordereddict>`_ that behaves like a > sequence as well as a dictionary. It allows > slicing and the keys, values and items methods > are special sequence objects (which are also > callable and so behave as methods too). > > What's New ? > ========== > > Code > ------- > > Removed the TODO and CHANGELOG sections in the > tail docstring (they are in the docs anyway). > > Disabled warnings during tests. > > Explicitly disabled tests execution on Python > v.2.2 . In addition to the slicing tests, other > ones are failing. > > Removed code duplication between the > ``__init__`` and the ``update`` methods. > > Misc. cleanup. > > Also, based on code from `Tim Wegener`_: > > - added the ``rename`` method; > - removed a ``has_key`` usage in the > ``__setitem__`` method. > > > Documentation > ---------------------- > > Moved the ISSUES chapter from code's tail > docstring to here. > > Moved up the `Creating an Ordered Dictionary > creating-an-ordered-dictionary>`_ chapter. > > Added prompts to the code examples and removed > the superfluous print statements (sometimes > they were there, sometimes they were not). > > Misc. cleanup. > > .. [#] So either no-one is using it, or it's > really good... From timothy at open-networks.net Thu Nov 16 07:10:43 2006 From: timothy at open-networks.net (timmy) Date: Thu, 16 Nov 2006 22:10:43 +1000 Subject: Secure Python In-Reply-To: References: <455c1665@quokka.wn.com.au> <455c4d9b@quokka.wn.com.au> Message-ID: <455c54c4$1@quokka.wn.com.au> Stephan Kuhagen wrote: > timmy <"timothy at open-networks.net"> wrote: > > This sub-thread starts to become a flame-war, isn't it? Calm down, both of > you... No need to fight, when only some ideas for a technical question are > requested. i'm not fighting, sometimes i can be a little terse for that i aplogise. > > >>as posted before, linux kernel limit. >> >>then you and your users can go as crazy as you want and you won't take >>out your system. > > > The problem with linux kernel limits are, that they won't work really good > on MacOSX and Windows... OTOH the idea is the right one, but the effect can > be achieved inside of Python. Since Python does byte compile the code and > the interpreter evaluates each byte code token in one evaluation step. The > interpreter could be extended for such usecases to count and limit the > number of evaluation steps allowed for untrusted script or methods in > untrusted script as well as to limit the recursion depth or memory to be > allocated. idunno sounds like a lot of trouble to engineer a solution that has already got a solution. all win NT systems have resource managment and i imagine OS X would as well?? > > Regards > Stephan > From beliavsky at aol.com Thu Nov 16 13:05:24 2006 From: beliavsky at aol.com (Beliavsky) Date: 16 Nov 2006 10:05:24 -0800 Subject: accessing fortran modules from python References: <1163696370.036741.274000@b28g2000cwb.googlegroups.com> Message-ID: <1163700324.197503.35450@f16g2000cwb.googlegroups.com> sam wrote: > hello all, > > i am currently in the process of planning a piece of software to model > polymerisation kinetics, and intend to use python for all the > high-level stuff. the number-crunching is something i would prefer to > do in fortran (which i have never used, but will learn), but i have no > experience of accessing non-python code from python. I strongly recommend learning Fortran 95, rather than Fortran 77 > i am also fairly new to programming period, and am therefore tackling a fairly serious > issue reletive to my experience. > > how easy is it to get fortran modules running from python? G95 is a good, free Fortran 95 compiler -- I use it heavily, on Windows. A discussion of "How to interface with Python programs" using numpy is at http://www.g95.org/howto.html#python . There is a numpy group http://groups.google.com/group/Numpy-discussion with a recent thread "accessing FORTRAN from Python". There is also a g95 group http://groups.google.com/group/gg95 . > if c is easier to use in this respect, i could go in that direction instead. easier to interface with Python, but not easier for writing numerical code IMO, especially if you need multidimensional arrays. > PS if numpy is adequate for this, i would be quite happy to use it. i > got the impression it was more for matrix algebra. i will be > programming a monte carlo simulation, which will need to perform a lot > (a lot!) of simple operations over and over... Fortran 95 has some of the advantages of numpy -- you perform operations on whole arrays and array sections. It would probably be considerably faster for code with loops. From antroy at gmail.com Thu Nov 23 10:36:36 2006 From: antroy at gmail.com (Ant) Date: 23 Nov 2006 07:36:36 -0800 Subject: Pyparsing Question. In-Reply-To: <4h_8h.1571$_H5.1426@tornado.texas.rr.com> References: <1164188646.047093.182390@f16g2000cwb.googlegroups.com> <4h_8h.1571$_H5.1426@tornado.texas.rr.com> Message-ID: <1164296196.242689.207090@j72g2000cwa.googlegroups.com> > Welcome to pyparsing! The simplest way to implement a markup processor in > pyparsing is to define the grammar of the markup, attach a parse action to > each markup type to convert the original markup to the actual results, and > then use transformString to run through the input and do the conversion. > This discussion topic has some examples: > http://pyparsing.wikispaces.com/message/view/home/31853. Thanks for the pointers - I had a look through the examples on the pyparsing website, but none seemed to show a simple example of this kind of thing. The discussion topic you noted above is exactly the sort of thing I was after! Cheers, From __peter__ at web.de Tue Nov 14 09:21:37 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Nov 2006 15:21:37 +0100 Subject: Programmatically finding "significant" data points References: <1163513101.580610.151420@b28g2000cwb.googlegroups.com> Message-ID: erikcw wrote: > Hi all, > > I have a collection of ordered numerical data in a list. The numbers > when plotted on a line chart make a low-high-low-high-high-low (random) > pattern. I need an algorithm to extract the "significant" high and low > points from this data. > > Here is some sample data: > data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, > 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, > 0.10] > > In this data, some of the significant points include: > data[0] > data[2] > data[4] > data[6] > data[8] > data[9] > data[13] > data[14] > .... > > How do I sort through this data and pull out these points of > significance? I think you are looking for "extrema": def w3(items): items = iter(items) view = None, items.next(), items.next() for item in items: view = view[1:] + (item,) yield view for i, (a, b, c) in enumerate(w3(data)): if a > b < c: print i+1, "min", b elif a < b > c: print i+1, "max", b else: print i+1, "---", b Peter From scheols at gmail.com Thu Nov 30 00:02:15 2006 From: scheols at gmail.com (Scheol Service) Date: Wed, 29 Nov 2006 23:02:15 -0600 Subject: Python Question About Compiling. In-Reply-To: <5b0fce7a0611292057p4d429226v9d3416ac9712e2@mail.gmail.com> References: <5b0fce7a0611292057p4d429226v9d3416ac9712e2@mail.gmail.com> Message-ID: <5b0fce7a0611292102g4a345b49h2a6e9c1f51ab4003@mail.gmail.com> ---------- Forwarded message ---------- From: Scheol Service Date: Nov 29, 2006 10:57 PM Subject: Python Question About Compiling. To: mailto:python-list at python.org Im just unsure on how to compile python code into .exe executionable files. Is there a simple way to do this? From horpner at yahoo.com Fri Nov 17 16:03:43 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 17 Nov 2006 22:03:43 +0100 Subject: remove a list from a list References: <455E0046.1090005@tim.thechases.com> <455E0A20.9000509@tim.thechases.com> <455E100D.8030100@tim.thechases.com> Message-ID: On 2006-11-17, Rares Vernica wrote: > Sorry for not being clear from the beginning and for not using > clear variable names. > > Problem context: > > import os > dirs_exclude = set(('a', 'b', 'e')) > for root, dirs, files in os.walk('python/Lib/email'): > # Task: > # delete from "dirs" the directory names from "dirs_exclude" > # case-insensitive > > The solution so far is: > > for i in xrange(len(dirs), 0, -1): > if dirs[i-1].lower() in dirs_exclude: > del dirs[i-1] > > I am looking for a nicer solution. I'd probably just skip over those dirs as I came them instead of troubling about mutating the list. Unless the list is needed in more than one place. -- Neil Cerutti From sjmachin at lexicon.net Thu Nov 30 20:33:47 2006 From: sjmachin at lexicon.net (John Machin) Date: 30 Nov 2006 17:33:47 -0800 Subject: String formatters with variable argument length References: <1164932769.210948.289560@f1g2000cwa.googlegroups.com> Message-ID: <1164936827.570682.325260@j72g2000cwa.googlegroups.com> Fredrik Tolf wrote: > On Thu, 2006-11-30 at 16:26 -0800, John Machin wrote: > > Fredrik Tolf wrote: > [...] > > > The thing is, I want to get format strings from the user, and I don't > > > want to require the user to consume all the arguments. docs.python.org > > > doesn't seem to have any clues on how to achieve this, and I can't think > > > of what to google for. > > > > Three approaches spring to mind. In descending order of my preference: > > > > (a) don't do that > > It would be a possibility, since all current uses actually do have the > right number of parameters. I would just like to keep the option > available. > > > (b) parse the format string, counting the number of args required. If > > the user has supplied more, throw them away. > > I was thinking of that, but it just seems far too ugly. what's ugly about this: [untested]: def count_format_args(s): pending = False count = 0 for c in s: if c == "%": # doubled % chars aren't counted pending = not pending elif pending: count += 1 pending = False return count output = format % arglist[:count_format_args(format)] > > > (c) wrap your execution of format_string % args in a try/except > > bracket. If you get a TypeError with that message [not guaranteed to > > remain constant in the future], throw away the last arg and go around > > again. > > That might be a good possibility. Thanks for the idea! I do consider it > quite a bit ugly, but that often happens when languages try to police > programmers... :P > > > As a matter of curiosity, why don't you want the user to consume all > > the arguments? Don't they get even a teensy-weensy warning message? Are > > you writing a Perl interpreter in Python? > > Well basically, I'm rewriting a autodownloader for a file-sharing > network in Python (previously written as a bash script, using the printf > command), and I have a number of files scattered over my hard drive > specifying search expressions, into which a potentially optional episode > number can be inserted using sprintf-like arguments (using > fsexpr="`printf "$sexpr" "$curep"`" in bash). I would like to keep it as > a printf parameter, in order to be able to write e.g. %02i, and I would > like to keep it optional, for downloading non-episoded stuff. > > I couldn't help noticing that the named variant of the % operator (using > a dict, that is) doesn't require all its arguments to be consumed. Using > that would require me to rewrite *all* the existing files, though. So offer the named variant as an option for new users or new uses by old users. Cheers, John From jackdied at jackdied.com Mon Nov 27 15:21:42 2006 From: jackdied at jackdied.com (Jack Diederich) Date: Mon, 27 Nov 2006 15:21:42 -0500 Subject: bz2.readline() slow ? In-Reply-To: References: Message-ID: <20061127202141.GC5353@performancedrivers.com> On Fri, Nov 24, 2006 at 10:11:06AM +0000, Soeren Sonnenburg wrote: > Dear all, > > I am a bit puzzled, as > > -----snip----- > import bz2 > f=bz2.BZ2File('data/data.bz2'); > > while f.readline(): > pass > -----snip----- > > takes twice the time (10 seconds) to read/decode a bz2 file > compared to > > -----snip----- > import bz2 > f=bz2.BZ2File('data/data.bz2'); > x=f.readlines() > -----snip----- > > (5 seconds). This is even more strange as the help(bz2) says: > > | readlines(...) > | readlines([size]) -> list > | > | Call readline() repeatedly and return a list of lines read. > | The optional size argument, if given, is an approximate bound on the > | total number of bytes in the lines returned. > > This happens on python2.3 - python2.5 and it does not help to specify a > maximum line size. > > Any ideas ? The bz2 module is implemented in C so calling "f.readline()" repeatedly has extra Python => C call overhead that "f.readlines()" doesn't have because it stays in a tight C loop the whole time. -Jack From rridge at csclub.uwaterloo.ca Tue Nov 7 14:49:30 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 7 Nov 2006 11:49:30 -0800 Subject: Exploiting Dual Core's with Py_NewInterpreter's separated GIL ? References: <1162553923.574732.305190@i42g2000cwa.googlegroups.com> <7xk62ct5pf.fsf@ruckus.brouhaha.com> <1162913881.953664.254960@m73g2000cwd.googlegroups.com> <1162922230.992249.52430@f16g2000cwb.googlegroups.com> <4550cc64$0$3462$9b622d9e@news.freenet.de> Message-ID: <1162928970.223276.72600@h48g2000cwc.googlegroups.com> Martin v. L?wis wrote: > How would you propose to fix file_repr to prevent such > a race condition? The race condition you describe is different from the one Joe Seigh described. It's caused because without GIL access to the file object is no longer thread safe, not because reference counting isn't thread safe. Ross Ridge From gabor at nekomancer.net Thu Nov 16 18:09:56 2006 From: gabor at nekomancer.net (gabor) Date: Fri, 17 Nov 2006 00:09:56 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: <455CED78.1060604@v.loewis.de> References: <455CED78.1060604@v.loewis.de> Message-ID: Martin v. L?wis wrote: > gabor schrieb: > >> or am i using os.listdir the "wrong way"? how do other people deal with >> this? > > You didn't say why the behavior causes a problem for you - you only > explained what the behavior is. > > Most people use os.listdir in a way like this: > > for name in os.listdir(path): > full = os.path.join(path, name) > attrib = os.stat(full) > if some-condition: > f = open(full) > ... > > All this code will typically work just fine with the current behavior, > so people typically don't see any problem. > i am sorry, but it will not work. actually this is exactly what i did, and it did not work. it dies in the os.path.join call, where file_name is converted into unicode. and python uses 'ascii' as the charset in such cases. but, because listdir already failed to decode the file_name with the filesystem-encoding, it usually also fails when tried with 'ascii'. example: >>> dir_name = u'something' >>> unicode_file_name = u'\u732b.txt' # the japanese cat-symbol >>> bytestring_file_name = unicode_file_name.encode('utf-8') >>> >>> >>> import os.path >>> >>> os.path.join(dir_name,unicode_file_name) u'something/\u732b.txt' >>> >>> >>> os.path.join(dir_name,bytestring_file_name) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/posixpath.py", line 65, in join path += '/' + b UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 1: ordinal not in range(128) >>> gabor From gagsl-py at yahoo.com.ar Mon Nov 13 14:08:41 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 13 Nov 2006 16:08:41 -0300 Subject: Find how to embed the BitTorrent in my program In-Reply-To: <455887AA.9080802@gmail.com> References: <455887AA.9080802@gmail.com> Message-ID: <7.0.1.0.0.20061113160812.03eb0b88@yahoo.com.ar> At Monday 13/11/2006 11:56, ?? ?????? wrote: >Is there any module can easy embed the BitTorrent(both tracker and >client) in myself's program . >Or where can find the documents for reuse official BitTorrent . Tried downloading the source? -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From CRhode at LacusVeris.com Thu Nov 30 09:37:54 2006 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Thu, 30 Nov 2006 08:37:54 -0600 Subject: PythonTidy In-Reply-To: References: Message-ID: <20061130143754.GD3322@loki> Roberto Bonvallet wrote this on Thu, Nov 30, 2006 at 01:21:55PM +0000. My reply is below. > About changing the shebang line: I'll take it as a bug. > About changing the encoding declaration from vim-style to > emacs-style: I'll take it as an insult :) Ooh! > Both are comments, and should be left that way. Besides, there is no > officially preferred way for each of them. BTW, in a recent thread on > this newsgroup, most people said they preferred #!/usr/bin/env python over > #!/usb/bin/python for the shebang line. See http://tinyurl.com/yngmfr . Thanks for the link. I was unaware of the /usr/bin/env technique and the controversy surrounding it. Thanks, too, for trying *PythonTidy*. As you have no doubt perceived, *PythonTidy* is *not* "table driven." It is a script after all. I decided before writing it that I didn't really need to externalize all the options; nevertheless, most are declared near the beginning where they sit just begging for end-user involvement. See: CODING_SPEC and SHEBANG. *PythonTidy* is all about consistency, consistency, and consistency. You can use it to standardize shebangs and coding across a whole library of Python scripts. -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 25? ? Wind NW 13 mph From soring at gmail.com Wed Nov 22 18:04:33 2006 From: soring at gmail.com (soring at gmail.com) Date: 22 Nov 2006 15:04:33 -0800 Subject: Accessing feed history in an RSS Reader References: <1164226615.555781.169150@m73g2000cwd.googlegroups.com> Message-ID: <1164236673.236541.21600@e3g2000cwe.googlegroups.com> I'm pretty sure that GoogleReader keeps its own archive on their servers to provide historical feed items - so you'd have to implement your own archiving on your server to get the same functionality (unless GoogleReader publishes any API you could use for this purpose). In the general case, given any XYZ company that publishes RSS for their web content, they of course don't have any obligation to keep archives of their past RSS feeds. Sorin Mark S. wrote: > Anyone know how to access feed history (items not contained in the > current .xml file), so that an RSS Reader could display historical > postings? Google Reader is able to do this. I'm interested in > implementing kind of feature in Python. I've done quite a bit of > searching to no avail. Any ideas? From no-spam at no-spam-no-spam.invalid Thu Nov 16 15:47:45 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 16 Nov 2006 21:47:45 +0100 Subject: numpy/scipy: error of correlation coefficient (clumpy data) In-Reply-To: <1163691740.158339.135610@m73g2000cwd.googlegroups.com> References: <1163351475.742836.311180@h48g2000cwc.googlegroups.com> <1163373385.596233.102100@k70g2000cwa.googlegroups.com> <1163640918.373134.285490@m7g2000cwm.googlegroups.com> <1163691740.158339.135610@m73g2000cwd.googlegroups.com> Message-ID: sturlamolden wrote: > robert wrote: > >> Think of such example: A drunken (x,y) 2D walker is supposed to walk along a diagonal, but he makes frequent and unpredictable pauses/slow motion. You get x,y coordinates in 1 per second. His speed and time pattern at all do not matter - you just want to know how well he keeps his track. > > > In which case you have time series data, i.e. regular samples from p(t) > = [ x(t), y(t) ]. Time series have some sort of autocorrelation in the > samples as well, which must be taken into account. Even tough you could > weight each point by the drunkard's speed, a correlation or linear > regression would still not make any sense here, as such analyses are > based on the assumption of no autocorrelation in the samples or the > residuals. Correlation has no meaning if y[t] is correlated with > y[t+1], and regression has no meaning if the residual e[t] is > correlated with the residual e[t+1]. > > A state space model could e.g. be applicable. You could estimate the > path of the drunkard using a Kalman filter to compute a Taylor series > expansion p(t) = p0 + v*t + 0.5*a*t**2 + ... for the path at each step > p(t). When you have estimates for the state parameters s, v, and a, you > can compute some sort of measure for the drunkard's deviation from his > ideal path. > > However, if you don't have time series data, you should not treat your > data as such. > > If you don't know how your data is generated, there is no way to deal > with them correctly. If the samples are time series they must be > threated as such, if they are not they should not. If the samples are > i.i.d. each point count equally much, if they are not they do not. If > you have a clumped data due to time series or lack of i.i.d., you must > deal with that. However, data can be i.i.d. and clumped, if the > underlying distribution is clumped. In order to determine the cause, > you must consider how your data are generated and how your data are > sampled. You need meta-information about your data to determine this. > Matlab or Octave will help you with this, and it is certainly not a > weakness of NumPy as you implied in your original post. There is no way > to put magic into any numerical computation. Statistics always require > formulation of specific assumptions about the data. If you cannot think > clearly about your data, then that is the problem you must solve. yes, in the example of the drunkard time-series its possible to go to better model - yet even there it is very expensive (in relation to the stats-improvement) to worry too much about the best model for such guy :-). In the field of datamining with many datatracks and typically digging first for multiple but smaller correlations - without a practical bottom-up modell, I think one falls regularly back to a certain basic case - maybe the most basic model for data at all: that basic modell is possibly that of a "hunter" which waits mostly, but only acts, if rare goodies are in front of him. Again in the most basic case, when having 2D x,y data in front of you without a relyable time-path or so, you see this: a density distribution of points. There is possibly a linear correlation on the highest scale - which you are interested in - but the points show also inhomgenity/clumping, and this rises the question of influence on r_err. What now? One sees clearly that its nonsense to make just plain average stats. I think this case is a most basic default for data - even compared to the common textbook-i.i.d. case. In fact, one can recognize such kind of stats, which repects mere (inhomogous) data-density itself, as (kind of simple/indepent) auto-bayesian stats vs. dumb averaging. I think one can almost always do this "bayesian density weighter/filter" as better option compared to mere average stats in that case of x,y correlation when there is obvioulsy interesting correlation but where you are too lazy..to..principally unable to itch out a modell on physics level. The latter requirement is in fact what any averaging stats cries for at any price - but how often can you do it in real world applications ... ( In reality there is anyway no way to eliminate auto-correlation in the composition of data. Everything and everybody lies :-) ) Thats where a top-down (model-free) bayesian stats approach will pay off: In the previous extreme example of criminal data duplication - I'm sure - it will totally neutralize the attack without question. In the drunkard time-series example it will tell me very reliably how well this guy will keep track - without need for a complex model. In the case of good i.i.d. data distribution it will tell me the same as simple stats. Just good news ... Thus I can possibly say it so now: I have the problem for guessing linear correlation (coefficient with error) on x,y data with respect to the (most general assupmtion) "bayesian" background of inhomogenous data distribution. Therefore I'm seeking a (fast/efficient/approx.) formula for r/r_err. I guess the formula for r does not change (much) compared to that for simple averaging stats, but the formula for r_err will. Maybe its easy with some existing means of numpy/scipy already. Maybe not. I'm far from finding the (efficient) math myself, but I know what I want - and can see if a formula really does it. Robert From ak at silmarill.org Fri Nov 3 00:20:43 2006 From: ak at silmarill.org (Rainy) Date: 2 Nov 2006 21:20:43 -0800 Subject: a newbi problem: can't find complete python curses library In-Reply-To: References: Message-ID: <1162531243.194489.99510@b28g2000cwb.googlegroups.com> krishnakant Mane wrote: > hello, > I am a new member to this list. > I am Krishnakant from India, Mumbai. > I have been coding in python for quite some time and now I am at the > intermediate level of programming as far as python is concerned. > I am going to develop a accounting software that can work on the > console and accessed through ssh from other terminals. > I will like to use the curses or ncurses library for the menus and the > input forms with add, save, delete, update and cancel buttens. > I also need to create drop down menus with a top level menu bar. > I read a few articles about python wrapping curses but can't find some > thing very comprehencive. > my question is, > does python possess a complete wrapper to ncurses and its related > libraries like menu, panel and form? > if yes then where can I find documentation? > I read the python documentation and could manage to find out the > window object but nothing on menus and panels and forms. > thanks and regards. > Please help, > Krishnakant. How about this short intro? www.ibm.com/developerworks/linux/library/l-python6.html It looks like it's got something about menus. Google returns many hits for 'python curses', you might want to go through the first few pages of results if you haven't yet. From will at willNOmcguganSPAM.com Thu Nov 23 14:44:38 2006 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Thu, 23 Nov 2006 19:44:38 +0000 Subject: Python 2.5 idle and print command How do I suppress a line feed? In-Reply-To: <1164310576.767673.297470@h54g2000cwb.googlegroups.com> References: <1164310576.767673.297470@h54g2000cwb.googlegroups.com> Message-ID: <4565fa04$0$1386$da0feed9@news.zen.co.uk> notejam wrote: > Hi, > I am having a problem with print statements always cause a line feed. > I need to print a line of text, then the next print statement will > start printing where the last one stopped rather than drop down a line. > > In basic we can do this with print "texst"; followed by next command > print "text2" > So how do I do that in python? > Or if you want to get rid of the space... import sys sys.stdout.write("texst") sys.stdout.write("text2") -- -- work: http://www.kelpiesoft.com blog: http://www.willmcgugan.com From paul at boddie.org.uk Fri Nov 24 06:32:44 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 24 Nov 2006 03:32:44 -0800 Subject: Pimping the 'cgi' module (was: Re: python gaining popularity according to a study) References: <1164306918.845529.95820@f16g2000cwb.googlegroups.com> Message-ID: <1164367964.527037.260690@45g2000cws.googlegroups.com> Christoph Haas wrote: > On Thursday 23 November 2006 21:29, robert wrote: > > When a LAMP programmer comes to Python, there are so many different > > confusing things. It starts with a 'non-documented' cgi module - a > > 'High-Level-Interface', that cannot even iterate over the form items. A > > name ZOPE in focus which reveals to be a monster system with 2-year > > learning-curve, ready for running an article editorial system for TOP-10 > > newspaper companies, but unable to make simple things simple. Zope was simultaneously one of the best things to happen in Python Web programming, but also one of the worst, mostly because people saw the power of the solution, correctly realised that it could do a lot of things they would otherwise have to do themselves, but then got locked into an approach which wasn't suitable for every kind of application. It was like having a handful of fairly promising parties ruined by the opening night of an expensive nightclub where the first two drinks were free. > > A handful of different Djangos - choose one for each weekday and programmer ... The handful of Djangos isn't necessarily a problem, but there is this "all or nothing" mentality in writing and promoting Web frameworks. Or rather, an "all or lots of little pieces" mentality. One is left either with a room full of tiny Lego bricks to put together, or one actually has to be the python and swallow a large solution whole, hoping that it all tastes good - even the nasty parts. > > And Ruby made it with this single-known simple URL-to-method-router (And > > possibly when coming from PHP & Perl one recognizes ::@$_$%??%/&... and > > the old namespace dirt) If there would have been a good cgi-system and a > > somewhat comfortable advanced URL-to-OO-router (beyond the socket > > wrapper HTTPServer) well exposed in the Python standard lib, the numbers > > would be probably very different today ... There was probably a window of opportunity to include the old Bobo dispatcher (or perhaps the "Poor Man's Zope" stuff) in the standard library, but rigid dispatchers of that style arguably aren't sufficient any more, even though they can be regarded almost as the original "URL-to-OO router". If you look now, there are a number of dispatchers/routers that work in a more-or-less independent way from frameworks, however. > I can fully second that. Coming from Perl and being used to the CGI module > that is de-facto standard and already doing things much better than > Python's equivalent my first thought was: "Does Python really expect me to > re-invent the wheel to write basic CGIs?" So I started creating > cookie-based session handlers, form field handling etc. The standard library expects you to do that, yes, since many of the Web-related modules were written in the infancy of the Web and have only been conservatively updated since. I remember when the cookie handling went in, and it was a big but overdue event back then. > I rather rely on the standard library unless it's really saving me time and worth learning > another language. Are frameworks perhaps even telling that the standard > library is still lacking in some way? I believe so, and I'm not alone with that opinion. > I'm thinking of features like: [List of HTTP-related, persistence-related and templating-related things] > I'm ready to invest work and ideas if anyone else is interested. Take a look at this page for some other work with similar goals: http://wiki.python.org/moin/WebStandardisation > Perhaps some day it makes it into the standard library or at least gives us > something between the features of the standard library and huge framework > monsters - something people can be pointed at when starting with Python > and CGIs. I'll probably do that anyway because my web projects all use > their own reinvented wheel and I'm losing the overview. And even Perl has > come that route - it started with a cgi-lib.pl which later became > the 'CGI' standard module. Some people will argue that you just want a big framework (implying that they know what you want better than you do), whilst others will talk about lots of reusable middleware. I don't disagree with the component-based solution mindset, but the bricks really have to be bigger, and there needs to be a picture on the box showing what the finished model looks like, along with some clear instructions on getting started. > Is it just a matter of lacking resources or interest? Even if there is no > interest I'll probably read "man CGI" and "man CGI::Session" again and > start implementing something nifty for ex-perlies like myself. Hmmm, > batteries included even for CGI programmers, a man can dream. :) I am aware of at least one person who seems dissatisfied with the current level of standardisation and who wants something a bit more obvious for those who don't want to take the "30 second Wiki" route. Perhaps they could openly publish their ideas or proposals and we could establish some kind of unofficial standard around those things. I'd certainly be interested in moving things forward in that regard. Paul From ogbash at gmail.com Thu Nov 30 11:58:56 2006 From: ogbash at gmail.com (ogbash at gmail.com) Date: 30 Nov 2006 08:58:56 -0800 Subject: Why are slice indices the way they are in python? In-Reply-To: <1164860915.349821.309920@14g2000cws.googlegroups.com> References: <1164860915.349821.309920@14g2000cws.googlegroups.com> Message-ID: <1164905936.794174.299200@l12g2000cwl.googlegroups.com> > Why? It doesn't seem intuitive to me. To me, it makes it harder, not > easier, to work with slices than if indexing started at 1 and the > above expression got you the 2nd throught the 5th character. Zero-based indices and excluding last index often works nicer, it is not the rule, but all my experience says that. a[i:i] is very handy to have in many algorithms, so you don't have to exclude this case explicitly. Index starting at 1 or including N often adds +-1 expressions to the code. I think that http://en.wikipedia.org/wiki/Modular_arithmetic makes it more intuitive. And if talking about dates, then I suggest NEVER use 2006-12-31 23:59:59 in data, always 2007-01-01 00:00:00 instead. If customer wants to see former on the screen just substruct 1 millisecond from the data and round it to what is needed. It makes all arithmetics, finding period collapses, time differences, etc much more painless. You sometimes don't even know if your database supports seconds, milliseconds, microseconds and what your operating system and programming language support. So if you are using inclusive end date you may find yourself in trouble very soon. Again, its not intuitive for ordinary people, but math people and programmers often find 0-based and exlusive ends are nicer to work with, at least me :) > Another thing that I've been puzzling over is the pow() function. > > pow(x,y) gives x**y. Fine. > > But pow(x,y,z) gives (x**y) % c > > I'm curious to know what the pressing reason for such a feature was. This makes cryptography code 100 times faster. Oleg From arkanes at gmail.com Thu Nov 30 16:34:14 2006 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 30 Nov 2006 15:34:14 -0600 Subject: Beautiful Soup Question: Filtering Images based on their width and height attributes In-Reply-To: <1164919424.990637.98000@h54g2000cwb.googlegroups.com> References: <1164919424.990637.98000@h54g2000cwb.googlegroups.com> Message-ID: <4866bea60611301334u6fc24f51jc202c491e5024048@mail.gmail.com> On 30 Nov 2006 12:43:45 -0800, PicURLPy wrote: > Hello, > > I want to extract some image links from different html pages, in > particular i want extract those image tags which height values are > greater than 200. Is there an elegant way in BeautifulSoup to do this? > Most image tags "in the wild" don't have height attributes, you have to download the image to see what size it is. > -- > http://mail.python.org/mailman/listinfo/python-list > From stefan.behnel-n05pAM at web.de Tue Nov 14 02:50:57 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 14 Nov 2006 08:50:57 +0100 Subject: HTML Parsing and Indexing In-Reply-To: <1163445129.232987.110300@e3g2000cwe.googlegroups.com> References: <1163445129.232987.110300@e3g2000cwe.googlegroups.com> Message-ID: <45597561.4030507@web.de> mailtogops at gmail.com wrote: > I am involved in one project which tends to collect news > information published on selected, known web sites inthe format of > HTML, RSS, etc and sortlist them and create a bookmark on our website > for the news content(we will use django for web development). Currently > this project is under heavy development. > > I need a help on HTML parser. lxml includes an HTML parser which can parse straight from URLs. http://codespeak.net/lxml/ http://cheeseshop.python.org/pypi/lxml Stefan From skip at pobox.com Wed Nov 8 15:56:08 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 8 Nov 2006 14:56:08 -0600 Subject: profanity on comp.lang.python (was Re: Pyro stability) In-Reply-To: <45522C3E.3050705@mvista.com> References: <1162694463.711859.200930@h48g2000cwc.googlegroups.com> <1162866001.849724.245510@b28g2000cwb.googlegroups.com> <1162997345.277966.31860@h48g2000cwc.googlegroups.com> <1163011320.632781.53370@m7g2000cwm.googlegroups.com> <45522C3E.3050705@mvista.com> Message-ID: <17746.17512.702626.550949@montanaro.dyndns.org> Carl> You are comparing interviews to usenet. I somehow see a Carl> disconnect. I don't think many people are going to go to a Carl> potential employer and say "hey fuck face, how the fuck are ya?" ... Carl> Although you mentioned impressing people etc, is it really Carl> important to impress people here by watching your P's and Q's? Carl> What impresses me here is someone's command of the language, I Carl> could really give a rats ass how they choose to disseminate their Carl> expertise. If recent news reports are to be believed (*) it would appear that companies are starting to check out prospective employees online. Granted, most of the stuff I've seen or heard relates to use of social networking sites like Facebook and MySpace, but I'm sure savvy employers looking for programming expertise would know to check out Usenet newsgroups and/or relevant mailing lists. Anything you post is fair game though. Also, "command of the language" can extend to the spoken/written word. Skip (*) http://www.nytimes.com/2006/06/11/us/11recruit.html?ei=5090&en=ddfbe1e3b386090b&ex=1307678400 From Jeff.Demel at JavelinDirect.com Wed Nov 15 10:47:07 2006 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Wed, 15 Nov 2006 09:47:07 -0600 Subject: Python v PHP: fair comparison? Message-ID: <136ED738BD4F1545B97E4AC06FF6370734BFC5@DMSP-MSG-EVS01.mail.pvt> -----Original Message----- Behalf Of walterbyrd The problem is that the system requirements for django and turbogears are sky-high. I think Django requires Apache 2.0 (and maybe mod_python 3.x), and CherryPy (part of turbogears) requires Python 2.4. If you are developing for a hosted environment, this can be a big problem. Few enough hosters provide python to begin with, then add to that such requirements as apache 2.0 - and you left with almost nothing. -------------------------- That's true, but I was lucky enough to find webfaction.com for python hosting, including Django. Good prices and they know Python. I think they used to be python-hosting.com or something. -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From tiedon_jano at hotmail.com Tue Nov 28 04:19:12 2006 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 28 Nov 2006 09:19:12 GMT Subject: Libgmail In-Reply-To: <1164703460.303062.58620@80g2000cwy.googlegroups.com> References: <1164703460.303062.58620@80g2000cwy.googlegroups.com> Message-ID: linuxfreak wrote: > hi guys, > > just starting out on python and libgmail... any documentation for > libgmail outthere... basically what i want to do is develop an > application to use gmail like and ftp server... should be able to > upload files and download them as well.... > > thanks > My browser has this amazing thing called Google installed. It's a kind of search facility with which I can search through Internet to find information. By searching for libgmail it gives me about 158000 places to read through but if I were you I'd start at the top which is libgmail.sourceforge.net HTH, Jussi From ratchetgrid at googlemail.com Sat Nov 25 09:19:29 2006 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Sat, 25 Nov 2006 14:19:29 +0000 Subject: Importing module of data dicts and constants Message-ID: <676224240611250619s764cb644kb254536e3f7aca2e@mail.gmail.com> Hi All, I ve got a single module which I m using to contain a lot of dictionaries, constants, general information, which are used by various other modules. However I can't seem to access them: in data.py _SEQTYPE_DNA = 0 _SEQTYPE_RNA = 1 _SEQTYPE_PROT = 2 _seqType = { "DNA":_SEQTYPE_DNA, "RNA":_SEQTYPE_RNA, "PROTEIN":_SEQTYPE_PROT } but in test.py from data import * class Test(object): def __init__(self, type): self.type = _seqType[type] def test(self): return self.type t = Test("DNA") print t.test() File "test.py", line 24, in __init__ self.type = _seqType[type] NameError: global name '_seqType' is not defined I think I m doing something incredibly wrong/stupid here.... Can anyone help? Many Thanks Nathan PS. I was wondering if the use of a data module to store constants and dictionaries is good design??? or not? From bituman at enerla.net Thu Nov 16 06:53:26 2006 From: bituman at enerla.net (bituman) Date: Thu, 16 Nov 2006 12:53:26 +0100 Subject: pyj file extension Message-ID: <455C5136.9000303@enerla.net> I have two questions for the list: - what extension is pyj ? - is there a good python debugger that can inspect precompiled python files? Thank you :) From kdotsky at gmail.com Tue Nov 28 16:44:01 2006 From: kdotsky at gmail.com (kdotsky) Date: 28 Nov 2006 13:44:01 -0800 Subject: urllib2 spinning CPU on read References: <1164531283.213844.243990@l39g2000cwd.googlegroups.com> <87odqse5bk.fsf@pobox.com> Message-ID: <1164750241.199679.45610@n67g2000cwd.googlegroups.com> > I didn't try looking at your example, but I think it's likely a bug > both in that site's HTTP server and in httplib. If it's the same one > I saw, it's already reported, but nobody fixed it yet. > > http://python.org/sf/1411097 > > > John Thanks. I tried the example in the link you gave, and it appears to be the same behavior. Do you have any suggestions on how I could avoid this in the meantime? From Thomas.Ploch at gmx.net Fri Nov 24 11:48:05 2006 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Fri, 24 Nov 2006 17:48:05 +0100 Subject: synching with os.walk() In-Reply-To: <1164384728.336225.59840@l39g2000cwd.googlegroups.com> References: <1164384728.336225.59840@l39g2000cwd.googlegroups.com> Message-ID: <45672245.7060609@gmx.net> >> os.walk() is a nice generator for performing actions on all files in a >> directory and subdirectories. However, how can one use os.walk() for walking >> through two hierarchies at once? I want to synchronise two directories (just >> backup for now), but cannot see how I can traverse a second one. I do this >> now with os.listdir() recursively, which works fine, but I am afraid that >> recursion can become inefficient for large hierarchies. > > I've run into wanting to work with parallel directory structures > before, and what I generally do is something like: > > for root, dirs, files in os.walk( dir1 ): > dir2_root = dir2 + root[len(dir1):] > for f in files: > dir1_path = os.path.join( root, f ) > dir2_path = os.path.join( dir2_root, f ) > Wouldn't it be better to implement tree traversing into a class, then you can traverse two directory trees at once and can do funny things with it? Thomas From nick at craig-wood.com Tue Nov 14 06:30:06 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 14 Nov 2006 05:30:06 -0600 Subject: Using signal.alarm to terminate a thread References: <12lgk7h55lu0vb4@corp.supernews.com> <12lj35aqa9drd8a@corp.supernews.com> Message-ID: Adrian Casey wrote: > > Adrian Casey wrote: > > import os, pexpect, threading > > > > def runyes(): > > print "Running yes command..." > > pexpect.run('yes', timeout=5) > > > > t = threading.Thread(target=runyes) > > t.start() > > t.join() > > > The timeout parameter will not work in this case. If you run the sample > code above, it will run forever. The above runs just fine for me, stopping after 5 seconds. Did you try it? > The 'yes' command presents a class of command which can not be > easily be handled by pexpect. Worked for me under Debian/testing. > As far as I know, mixing threads and signals is OK provided the > parent creates the alarm. There are so many pitfalls here that I advise you not to try. From the linuxthreads FAQ J.3: How shall I go about mixing signals and threads in my program? The less you mix them, the better. Notice that all pthread_* functions are not async-signal safe, meaning that you should not call them from signal handlers. This recommendation is not to be taken lightly: your program can deadlock if you call a pthread_* function from a signal handler! The only sensible things you can do from a signal handler is set a global flag, or call sem_post on a semaphore, to record the delivery of the signal. The remainder of the program can then either poll the global flag, or use sem_wait() and sem_trywait() on the semaphore. Another option is to do nothing in the signal handler, and dedicate one thread (preferably the initial thread) to wait synchronously for signals, using sigwait(), and send messages to the other threads accordingly. Note also that the signal can be delivered to any thread which complicates things. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From webraviteja at gmail.com Tue Nov 28 00:24:32 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 27 Nov 2006 21:24:32 -0800 Subject: Python script and C++ In-Reply-To: <456b83c7$1@clarion.carno.net.au> References: <456b83c7$1@clarion.carno.net.au> Message-ID: <1164691472.172783.151290@n67g2000cwd.googlegroups.com> Thuan Seah Tan wrote: > Hi all, > > I am new to python and currently I am working on a traffic simulation > which I plan to define the various agents using scripting. It's kind of like > scripting for non-playable character in games. I am thinking of using python > for this but I am concerned with running time. Is scripting a lot slower > compared to direct implementation in C++? Does compiling the script help in > any way? Python is perfectly suitable for this use. Python was in use in video games in this way when computers were a lot slower. I doubt that you will need to bother compiling the script or see any observable enhancement if you do. One example I can remember is Kingdom Under Fire (2001). From dandolls at yahoo.co.in Mon Nov 20 15:41:18 2006 From: dandolls at yahoo.co.in (amit saha) Date: Tue, 21 Nov 2006 02:11:18 +0530 Subject: GUI Design using BOA Constructor Message-ID: <1164055278.6643.1.camel@localhost> Hi list! I was designing a GUI App using BOA Constructor. I have designed the User Interface.However I cannot figure out how do i add the event handling code to the buttons and other controls Please help. -- Amit Saha *A proud Ubuntero* amitsaha.in.googlepages.com ,--(_) | | _/ ;-._\ | | |,-. | |,--. -+- | | (_)( ) ) | | | | | || | | | | \ ;-'_/ `--' `--' `--'' ' `- `--' -hrr- `--(_) Send instant messages to your online friends http://in.messenger.yahoo.com From xi at gamma.dn.ua Mon Nov 20 06:29:44 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Mon, 20 Nov 2006 13:29:44 +0200 Subject: A python IDE for teaching that supports cyrillic i/o In-Reply-To: <1163976873.100140.172880@j44g2000cwa.googlegroups.com> References: <1163935652.536330.240090@b28g2000cwb.googlegroups.com> <1163976873.100140.172880@j44g2000cwa.googlegroups.com> Message-ID: <20061120112944.GA23576@58sirius016.dc.ukrtel.net> On Sun, Nov 19, 2006 at 02:54:33PM -0800, Leo Kislov wrote: > Kirill Simonov wrote: > > On Sun, Nov 19, 2006 at 03:27:32AM -0800, Leo Kislov wrote: > > > IDLE on Windows works fine for your example in interactive console: > > > > > > >>> name = raw_input("What's your name? ") > > > > Have you tried to use cyrillic characters in a Python string in > > interactive console? When I do it, I get the "Unsupported characters in > > input" error. For instance, > > > > >>> print "??????" # That's "Hi" in Russian. > > Unsupported characters in input > > That works for me in Win XP English, with Russian locale and Russian > language for non-unicode programs. Didn't you say you want to avoid > unicode? If so, you need to set proper locale and language for > non-unicode programs. Thanks. After I set Russian language for non-unicode programs, the `print "??????"` expression started to work correctly. On the other hand, >>> print u"??????" doesn't display "??????". The output looks like a CP1251-encoded string was displayed using the latin1 character set. It seems that the interactive interpreter in IDLE uses the CP1251 codepage. > > Anyway, I just want the interactive console of an IDE to behave like a > > real Python console under a UTF-8 terminal (with sys.stdout.encoding == > > 'utf-8'). > > Do you realize that utf-8 locale makes len() function and slicing of > byte strings look strange for high school students? > > hi = u"??????".encode("utf-8") > r = u"?".encode("utf-8") > print len(hi) # prints 12 > print hi[1] == r # prints False > for char in hi: > print char # prints garbage No, it slipped off my mind... > As I see you have several options: > 1. Set Russian locale and Russian language for non-unicode programs on > Windows. I guess I will go this route. Looks that IDLE works reasonable well in CP1251 locale. Thanks, Kirill From inq1ltd at verizon.net Mon Nov 6 11:07:30 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Mon, 06 Nov 2006 11:07:30 -0500 Subject: how do I pass values between classes? In-Reply-To: <1162796443.570347.91760@e3g2000cwe.googlegroups.com> References: <1162592180.494470.257040@h54g2000cwb.googlegroups.com> <454C9ECF.5020806@websafe.com> <1162796443.570347.91760@e3g2000cwe.googlegroups.com> Message-ID: <200611061107.31106.inq1ltd@verizon.net> Kath, You can use this class to pass values around without concern for conflicts since it has no values of its own. class Kvariable: def setVariable(self, variable): self.output = variable def showVariable(self): print self.output x = Kvariable() y = Kvariable() x.setVariable("James_01") y.setVariable("Kath_01") x.showVariable() y.showVariable() x.setVariable('3.14159') y.setVariable("python.org") x.showVariable() y.showVariable() jim-on-linux http://www.inqvista.com On Monday 06 November 2006 02:00, kath wrote: > hi, Larry Bates .... thanks for the reply... > > > You might consider doing it the same way wx > > passes things around. When you instantiate > > the subclass pass the parent class' instance > > as first argument to __init__ method. > > Yes thats absolutely right.. > > > That way the subclass can > > easily pass values back to the parent by > > using that pointer. > > Could you please explain me this.. more > clearly. I think it is much close to the > solution. > > > Thank you. > regards, sudhir From fredrik at pythonware.com Wed Nov 22 02:37:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Nov 2006 08:37:43 +0100 Subject: Caution newbie question: python window to stay open ? In-Reply-To: <1164165632.072406.111580@f16g2000cwb.googlegroups.com> References: <1164165632.072406.111580@f16g2000cwb.googlegroups.com> Message-ID: mkengel wrote: > Problem: Python window closes immediately after executing a *.py file > (e.g. containing a "print..." command. > What do I have to do to keep it open to see the results ? Simple scripts that print to a console, or read from it, works best if you run them from a standard Command Prompt window. If you just click on a Python script in the explorer, Windows will create a temporary command window, and remove it when the program is done. This is standard Windows behaviour; to get around this in a general way, you need to write GUI-oriented Python programs (using e.g. Tkinter or wxPython), and run them using the "pythonw.exe" runtime. For simpler scripts, you can also add raw_input("Press return to close this window...") to the end of the script. For tips on running Python programs from the command prompt, this page might also be helpful: http://effbot.org/pyfaq/how-do-i-run-a-python-program-under-windows From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Nov 29 00:38:51 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 29 Nov 2006 06:38:51 +0100 Subject: Python program that validates an url against w3c markup validator References: <1164778181.910135.53070@j44g2000cwa.googlegroups.com> Message-ID: <4t4knbF1280olU1@mid.individual.net> yaru22 wrote: > I was looking at the python library and thought urllib or urllib2 > may be used to make this program work. > > But I don't know how to send my urls to the w3c validator and get > the result. Another great alternative is using the Twisted framework: Once you get familiar with the style of Twisted code, it's quite easy to many write clients and servers because most protocols are already implemented and must only be adapted to your needs. Regards, Bj?rn -- BOFH excuse #40: not enough memory, go get system upgrade From nobody at nowhere.org Mon Nov 27 20:10:57 2006 From: nobody at nowhere.org (Nobody) Date: Tue, 28 Nov 2006 03:10:57 +0200 Subject: MIME encoding change in Python 2.4.3 (or 2.4.2? 2.4.1?) - problem and solution Message-ID: <456B8CA1.30401@nowhere.org> I have an application that processes MIME messages. It reads a message from a file, looks for a text/html and text/plain parts in it, performs some processing on these parts, and outputs the new message. Ever since I recently upgraded my Python to 2.4.3, the output messages started to come out garbled, as a block of junk characters. I traced the problem back to a few lines that were removed from the email package: The new Python no longer encodes the payload when converting the MIME message to a string. Since my program must work on several computers, each having a different version of Python, I had to find a way to make it work correctly no matter if msg.as_string() encodes the payload or not. Here is a piece of code that demonstrates how to work around this problem: .................. code start ................ import email import email.MIMEText import email.Charset def do_some_processing(s): """Return the input text or HTML string after processing it in some way.""" # For the sake of this example, we only do some trivial processing. return s.replace('foo','bar') msg = email.message_from_string(file('input_mime_msg','r').read()) utf8 = email.Charset.Charset('UTF-8') for part in msg.walk(): if part.is_multipart(): continue if part.get_content_type() in ('text/plain','text/html'): s = part.get_payload(None, True) # True means decode the payload, which is normally base64-encoded. # s is now a sting containing just the text or html of the part, not encoded in any way. s = do_some_processing(s) # Starting with Python 2.4.3 or so, msg.as_string() no longer encodes the payload # according to the charset, so we have to do it ourselves here. # The trick is to create a message-part with 'x' as payload and see if it got # encoded or not. should_encode = (email.MIMEText.MIMEText('x', 'html', 'UTF-8').get_payload() != 'x') if should_encode: s = utf8.body_encode(s) part.set_payload(s, utf8) # The next two lines may be necessary if the original input message uses a different encoding # encoding than the one used in the email package. In that case we have to replace the # Content-Transfer-Encoding header to indicate the new encoding. del part['Content-Transfer-Encoding'] part['Content-Transfer-Encoding'] = utf8.get_body_encoding() file('output_mime_msg','w').write(msg.as_string()) .................. code end ................ Hope this helps someone out there. (Permission is hereby granted for anybody to use this piece of code for any purpose whatsoever) From chrisBrat at gmail.com Mon Nov 13 09:19:51 2006 From: chrisBrat at gmail.com (Chris Brat) Date: 13 Nov 2006 06:19:51 -0800 Subject: Python development time is faster. In-Reply-To: References: <1163425734.640509.99420@m73g2000cwd.googlegroups.com> Message-ID: <1163427591.207857.162050@e3g2000cwe.googlegroups.com> I work full time with Java, but downloaded python about a year ago and started playing. I've used it quite a few times in my working environment. From fredrik at pythonware.com Tue Nov 28 10:22:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 28 Nov 2006 16:22:30 +0100 Subject: Inheritance from builtin list and override of methods. In-Reply-To: <200611281631.38692.mgiann@beta-cae.gr> References: <200611261804.54669.mgiann@beta-cae.gr> <200611281631.38692.mgiann@beta-cae.gr> Message-ID: Michalis Giannakidis wrote: > I perfectly understand that this adds significant penalty to the execution of > code. But in the way things are, I have to know ( or guess ?) how its > function has been implemented. and that's different from how object orientation usually works in exactly what way? From bj_666 at gmx.net Tue Nov 28 06:47:32 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 28 Nov 2006 12:47:32 +0100 Subject: os.walk return hex excapes References: Message-ID: In , Alex S wrote: > os.walk return hex excape sequence inside a files name, and when i try > to feed it back to os.remove i get > > OSError: [Errno 22] Invalid argument: > 'C:\\Temp\\?p?\xbfS\xbf\xac?G\xaba ACDSee \xbb?a??n a???\xac\xb5\xbfn.exe' There is no hex escape in that file name, just in the representation you get in the error message. The `repr()` form of a string contains just ASCII, everything outside printable ASCII characters is printed as hex escape so you can see what the string actually contains without being interpreted by the shell, IDE or wherever the string is displayed. How does the real file name look like? Ciao, Marc 'BlackJack' Rintsch From mail at microcorp.co.za Tue Nov 21 11:01:22 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 21 Nov 2006 18:01:22 +0200 Subject: rpncalc-2.5 RPN Calculator for Python References: <1164009539.310173.248620@m7g2000cwm.googlegroups.com> <1164090836.703397.45350@k70g2000cwa.googlegroups.com> Message-ID: <000201c70dfe$ebe42440$03000080@hendrik> "John Machin" wrote: > Hendrik van Rooyen wrote: > > "John Machin" WROTE: > > > > > Hendrik van Rooyen wrote: > > > > "Raymond L. Buvel" wrote: > > > > > > > > > > > > > The rpncalc package adds an interactive Reverse Polish Notation (RPN) > > > > > > > > Can anyone remember who the Pole was and how his name is spelled? > > > > > > > > (no fair googling) > > > > > > Remember who: yes > > > Remember spelling: you must be joking; however I do remember that the > > > name is given in Knuth TAOCP vol 3 as a test case for the soundex > > > algorithm. > > > > > > name = u"\u0141ukasiewicz" # Python syntax so we're not completely OT > > > :-) > > > > > > The first letter is LATIN CAPITAL LETTER L WITH STROKE. > > > > Thanks - I find it disgusting that I am completely unable to remember this - > > > > If his name had been Smith or Jones it would be no problem, > > but just because there are a few too many consonants for me > > to handle, it is as if there is a total black hole... > > > > > > A *few* too many? By my count it's 6 consonants compared with 5 in "van > Rooyen". That makes it even more disgusting - that I should go "tilt" so easily... but this is way off topic now... - Hendrik From fredrik at pythonware.com Wed Nov 22 02:28:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Nov 2006 08:28:55 +0100 Subject: re.match -- not greedy? In-Reply-To: <750FA239330A7E4CA15D456F37DFF8AE02500B0C@XCH-AU-01.au.nos.boeing.com> References: <750FA239330A7E4CA15D456F37DFF8AE02500B0C@XCH-AU-01.au.nos.boeing.com> Message-ID: EXI-Andrews, Jack wrote: > > that's a misunderstanding of what a regular expression is, though: > > conceptually, a RE describes a set of strings, and the RE engine is > > designed to answer the question "does this string belong to this > > set". > if that's so, what is the point of +? and *? (?) to influence which string to pick from the set, when a target string can match multiple members. > seems to me it's a bit more pragmatic than pure set membership your assertion was that a RE should *fail* if you used greedy matching. that's not how RE's work. From billpaterson2006 at googlemail.com Tue Nov 14 05:32:06 2006 From: billpaterson2006 at googlemail.com (billpaterson2006 at googlemail.com) Date: 14 Nov 2006 02:32:06 -0800 Subject: Seeking assistance - string processing. Message-ID: <1163500326.492067.234080@k70g2000cwa.googlegroups.com> I've been working on some code to search for specific textstrings and act upon them insome way. I've got the conversion sorted however there is 1 problem remaining. I am trying to work out how to make it find a string like this "===" and when it has found it, I want it to add "===" to the end of the line. For example. The text file contains this: ===Heading and I am trying to make it be processed and outputted as a .dat file with the contents ===Heading=== Here's the code I have got so far. import string import glob import os mydir = os.getcwd() newdir = mydir#+"\\Test\\"; for filename in glob.glob1(newdir,"*.txt"): #print "This is an input file: " + filename fileloc = newdir+"\\"+filename #print fileloc outputname = filename outputfile = string.replace(outputname,'.txt','.dat') #print filename #print a print "This is an input file: " + filename + ". Output file: "+outputfile #temp = newdir + "\\" + outputfile #print temp fpi = open(fileloc); fpo = open(outputfile,"w+"); output_lines = [] lines = fpi.readlines() for line in lines: if line.rfind("--------------------") is not -1: new = line.replace("--------------------","----") elif line.rfind("img:") is not -1: new = line.replace("img:","[[Image:") elif line.rfind(".jpg") is not -1: new = line.replace(".jpg",".jpg]]") elif line.rfind(".gif") is not -1: new = line.replace(".gif",".gif]]") else: output_lines.append(line); continue output_lines.append(new); for line in output_lines: fpo.write(line) fpi.close() fpo.flush() fpo.close() I hope this gets formatted correctly :-p Cheers, hope you can help. From sturlamolden at yahoo.no Wed Nov 15 20:35:18 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 15 Nov 2006 17:35:18 -0800 Subject: numpy/scipy: error of correlation coefficient (clumpy data) In-Reply-To: References: <1163351475.742836.311180@h48g2000cwc.googlegroups.com> <1163373385.596233.102100@k70g2000cwa.googlegroups.com> Message-ID: <1163640918.373134.285490@m7g2000cwm.googlegroups.com> robert wrote: > here the bootstrap test will as well tell us, that the confidence intervall narrows down by a factor ~sqrt(10) - just the same as if there would be 10-fold more of well distributed "new" data. Thus this kind of error estimation has no reasonable basis for data which is not very good. The confidence intervals narrows when the amount of independent data increases. If you don't understand why, then you lack a basic understanding of statistics. Particularly, it is a fundamental assumption in most statistical models that the data samples are "IDENTICALLY AND INDEPENDENTLY DISTRIBUTED", often abbreviated "i.i.d." And it certainly is assumed in this case. If you tell the computer (or model) that you have i.i.d. data, it will assume it is i.i.d. data, even when its not. The fundamental law of computer science also applies to statistics: shit in = shit out. If you nevertheless provide data that are not i.i.d., like you just did, you will simply obtain invalid results. The confidence interval concerns uncertainty about the value of a population parameter, not about the spread of your data sample. If you collect more INDEPENDENT data, you know more about the population from which the data was sampled. The confidence interval has the property that it will contain the unknown "true correlation" 95% of the times it is generated. Thus if you two samples WITH INDEPENDENT DATA from the same population, one small and one large, the large sample will generate a narrower confidence interval. Computer intensive methods like bootstrapping and asymptotic approximations derived analytically will behave similarly in this respect. However, if you are dumb enough to just provide duplications of your data, the computer is dumb enough to accept that they are obtained statistically independently. In statistical jargon this is called "pseudo-sampling", and is one of the most common fallacies among uneducated practitioners. Statistical software doesn't prevent the practitioner from shooting himself in the leg; it actually makes it a lot easier. Anyone can paste data from Excel into SPSS and hit "ANOVA" in the menu. Whether the output makes any sense is a whole other story. One can duplicate each sample three or four times, and SPSS would be ignorant of that fact. It cannot guess that you are providing it with crappy data, and prevent you from screwing up your analysis. The same goes for NumPy code. The statistical formulas you type in Python have certain assumptions, and when they are violated the output is of no value. The more severe the violation, the less valuable is the output. > The interesting task is probably this: to check for linear correlation but "weight clumping of data" somehow for the error estimation. If you have a pathological data sample, then you need to specify your knowledge in greater detail. Can you e.g. formulate a reasonable stochastic model for your data, fit the model parameters using the data, and then derive the correlation analytically? I am beginning to think your problem is ill defined because you lack a basic understanding of maths and statistics. For example, it seems you were confusing numerical error (rounding and truncation error) with statistical sampling error, you don't understand why standard errors decrease with sample size, you are testing with pathological data, you don't understand the difference between independent data and data duplications, etc. You really need to pick up a statistics textbook and do some reading, that's my advice. From johnjsal at NOSPAMgmail.com Wed Nov 15 16:11:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 15 Nov 2006 16:11:00 -0500 Subject: Python-2.5.exe? In-Reply-To: References: Message-ID: <455b824d$0$7054$c3e8da3@news.astraweb.com> Fredrik Lundh wrote: > python doesn't depend on the registry settings for normal use, so > you can simply install python as usual, copy python25.dll from > c:\windows\system32 to c:\python25, and then copy (or move) the > entire c:\python25 tree to your USB drive. Is it safe to assume that if you do this, Python first looks in C:\Python25 for the dll file, before trying to find the non-existent (on the USB drive) C:\Windows\System32? Thanks. From apardon at forel.vub.ac.be Tue Nov 21 09:03:04 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 21 Nov 2006 14:03:04 GMT Subject: Misleading IOerror when opening a non-existent file for append? References: <1164037095.148334.157670@e3g2000cwe.googlegroups.com> <1164037676.537263.53480@f16g2000cwb.googlegroups.com> <1164109830.629768.51130@k70g2000cwa.googlegroups.com> Message-ID: On 2006-11-21, jkn wrote: > Hi there > Thanks for the comments. I see that I actually confused myself a > bit with my posting. It's been a while and I mistook the use of '/' as > a platform-independent directory delimiter with the use of '\\'. > > I also thought that I was seeing something similar on Windows and > Linux. This may not be the case ;-o. > > So, to try again. It looks as it the attempt to open a non-existent > file (for instance, because the parent folder does not exist) gives an > odd error on Linux but not on Windows. > > On Windows: > >> >>> f = file(r'c:\does-not-exist\DoesNotExist.txt','a') >> >> Traceback (most recent call last): >> File "", line 1, in >> f = file(r'c:\does-not-exist\DoesNotExist.txt','a') >> IOError: [Errno 2] No such file or directory: 'c:\\does-not-exist >> \\DoesNotExist.txt' >> >>> > > (replacing the '\' with '/' gives the same message, which is what I was > trying to convey) > > On Linux, you get the 'Bad mode' error. > > Strange?! Not on my box (Python 2.4.4c0): >>> open("nodir/nofile", "a") Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'nodir/nofile' -- Antoon Pardon From dakman at gmail.com Thu Nov 16 13:22:57 2006 From: dakman at gmail.com (dakman at gmail.com) Date: 16 Nov 2006 10:22:57 -0800 Subject: Is python for me? In-Reply-To: <455b395e$0$3184$426a34cc@news.free.fr> References: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> <1163441468.081643.189600@f16g2000cwb.googlegroups.com> <1163448523.712403.232970@i42g2000cwa.googlegroups.com> <1163530584.269684.214520@h48g2000cwc.googlegroups.com> <455b395e$0$3184$426a34cc@news.free.fr> Message-ID: <1163701377.322969.109090@h48g2000cwc.googlegroups.com> Yes of course python can handle of these things, but have you actually compared them to something written in C? Even if the app was converted into bytecode, it's still not as fast as an executable, that's all I am saying. Bruno Desthuilliers wrote: > dakman at gmail.com wrote: > > By large I mean an application with intensive operations, such as a > > fancy GUI maybe a couple of threads, accessing a database, etc. > > > > Threads are handled by the OS. GUI are (usually) handled by a > lower-level lib like GTK or such. DB access mostly rely on the > particular RDBMS. So we're left with the application code itself - the > glue between all these componants. There's usually nothing really > "intensive" here, and I wouldn't bet using C++ instead of Python would > make a huge difference here - wrt/ perceived performances at least. > > My 2 cents... > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From sthompson at creativewebnet.com Fri Nov 24 06:35:21 2006 From: sthompson at creativewebnet.com (Steve Thompson) Date: Fri, 24 Nov 2006 06:35:21 -0500 Subject: Active State and Komodo... Message-ID: Hello all, I was wondering the differnced there were betwee Active State's python and the open source version of python. Would I have to unistall my opend souce python? Additonally, how does Active State's Komodo IDE vs. the eric3 IDE unler SuSE Linux v. 10.i? Addionally, is the eric IDE (version 3) an acceptible IDE or are there more easy and more productive IDE's for perl? I'm urining Gnome v. 12.2.2 and Eric v 3.8.1 Thanks Steve From grante at visi.com Wed Nov 29 12:00:51 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Nov 2006 17:00:51 -0000 Subject: How to detect what type a variable is? References: <1164814586.113454.144090@l12g2000cwl.googlegroups.com> <1164818738.403393.112900@j44g2000cwa.googlegroups.com> Message-ID: <12mrf63pm47umef@corp.supernews.com> On 2006-11-29, eduardo.padoan at gmail.com wrote: > > Leandro Ardissone wrote: >> Hi, >> >> I want to know what type is a variable. >> For example, I get the contents of an xml but some content is a list or >> a string, and I need to know what type it is. > > You should try to treat it as a list, catch the exceptions raise when > it is a string (problably ValueError, TypeError ou Attribute error, > depends on what are you doing), As you said, it depends on what he's doing. The problem is that strings act a lot like lists, and if he's using the subset of list characteristics that are implimented by strings, there won't _be_ an exception -- just wrong results. In the past, I've almost alwasy had to look before I leap when dealing with both strings and lists. -- Grant Edwards grante Yow! How's it going in at those MODULAR LOVE UNITS?? visi.com From timothy at open-networks.net Thu Nov 16 19:11:38 2006 From: timothy at open-networks.net (timmy) Date: Fri, 17 Nov 2006 10:11:38 +1000 Subject: Secure Python In-Reply-To: <4s38t9Ftln2aU1@mid.uni-berlin.de> References: <455c1665@quokka.wn.com.au> <455c4d9b@quokka.wn.com.au> <4s38t9Ftln2aU1@mid.uni-berlin.de> Message-ID: <455cfdb8$1@quokka.wn.com.au> Diez B. Roggisch wrote: >>as posted before, linux kernel limit. >> >>then you and your users can go as crazy as you want and you won't take >>out your system. >> >>maybe you should think a little more before going on the attack like that. > > > You should maybe read a little bit more when making bold statements about > the feasibility of a sandboxed _PYTHON_. The OP wrote: > there is nothing preventing you putting limits on the resources each process uses, on just about any modern day OS > At least to me - and I presume pretty much everybody except you in this > thread - Oh no i understand perfectly what he wants, i merely suggest a simple OS based solution. this means that he is interested in executing arbitrary pieces of > python code inside the interpreter, which comes from e.g. players who > customize their in-game behavior of their avatars. > > Now how exactly does linux (or any other resource limiting technique on any > OS) help here - killing the whole game server surely isn't a desirable > solution when one player goes berserk, might it be intentionally or not. resource managment does not kill anything it merely prevents one process running away and consuming the whole server. this is EXACTLY what he is afraid of. if he intends on running arbitrary code then i suggest he spawns each one as a seperate thread with a spefic name and merely set limits on all processes named X. that way he can run any whacky code he wants safely inside those processes without fear of any one of them crashing the server. I know it can be done under any of the nix's, I'm not sure how to do so under windows, but it could probably be done. > > It is a recurring and pretty much understandable request on c.l.py to be > able to do so - sometimes it arises in the disguise of killable threads. > But unfortunately the solution doesn't seem to be as simple as one would > wish. i can understand people wanting an application based cross platform solution to this, but i'm yet to see anything practicle hence i suggest and OS based solution. > > Diez From researchbase at gmail.com Fri Nov 17 14:20:29 2006 From: researchbase at gmail.com (krishnakant Mane) Date: Sat, 18 Nov 2006 00:50:29 +0530 Subject: how to print pdf with python on a inkjet printer. In-Reply-To: References: Message-ID: On 17/11/06, Fredrik Lundh wrote: > http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html > > or possibly: > > http://www.planetpdf.com/forumarchive/49365.asp I can't figure out where is the win32api module in my system. I think I need to download it. I tried to search but did not find it. what is the url for this module and does it also have documentation. thanking you. Krishnakant. From steve at REMOVE.THIS.cybersource.com.au Thu Nov 23 06:34:18 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 23 Nov 2006 22:34:18 +1100 Subject: "10, 20, 30" to [10, 20, 30] References: <1164280390.745628.167770@k70g2000cwa.googlegroups.com> Message-ID: On Thu, 23 Nov 2006 03:13:10 -0800, Daniel Austria wrote: > Sorry, > > how can i convert a string like "10, 20, 30" to a list [10, 20, 30] > > what i can do is: > > s = "10, 20, 30" > tmp = '[' + s + ']' > l = eval(tmp) > > but in my opinion this is not a nice solution It is a dangerous solution if your data is coming from an untrusted source. >>> s = "10, 20, 30" >>> L = [x.strip() for x in s.split(',')] >>> L ['10', '20', '30'] >>> L = [int(x) for x in L] >>> L [10, 20, 30] Or, as a one liner: [int(x.strip()) for x in s.split(',')] -- Steven. From kinch1967 at gmail.com Wed Nov 29 01:47:51 2006 From: kinch1967 at gmail.com (bullockbefriending bard) Date: 28 Nov 2006 22:47:51 -0800 Subject: 6 Pick Bet Grouping In-Reply-To: <1164772251.325678.45990@l39g2000cwd.googlegroups.com> References: <1164768957.528355.210070@16g2000cwy.googlegroups.com> <1164772251.325678.45990@l39g2000cwd.googlegroups.com> Message-ID: <1164782871.330950.272460@j44g2000cwa.googlegroups.com> Sorry, I perhaps didn't frame my initial post very well. I hope my reply to your other post below has answered these questions. From fd0man at gmail.com Fri Nov 17 16:51:44 2006 From: fd0man at gmail.com (Michael B. Trausch) Date: Fri, 17 Nov 2006 16:51:44 -0500 Subject: Decimal() instead of float? In-Reply-To: References: <1163294604.4675.4.camel@pepper> <1163511997.4675.88.camel@pepper> <4559F828.7070704@holdenweb.com> <1163794251.5107.151.camel@pepper> Message-ID: <1163800304.5107.179.camel@pepper> On Fri, 2006-11-17 at 21:25 +0100, Fredrik Lundh wrote: > > Some of the lat/long pairs that I have used seem to come out fine, but > > some do not. Because the mathmatics used with them involve complex > > equations when determining distance and the like, any error gets > > massively compounded before a final result is evident. > > sorry, but I don't think you have the slightest idea what you're doing, > really. > Sure, I do. Let's say that I want to work with the latitude 33.6907570. In Python, that number can not be stored exactly without the aid of decimal.Decimal(). >>> 33.6907570 33.690756999999998 >>> As you can see, it loses accuracy after the 6th decimal place. That's not good enough: I have 8 numbers that need to be exact, and I am only getting six. That error will propagate throughout any multiplication or division problem. The error compounds itself: >>> x = 33.6907570 >>> x 33.690756999999998 >>> x*2 67.381513999999996 >>> Now, observe what happens when you compute it exactly: >>> from decimal import * >>> xx = Decimal('33.6907570') >>> xx Decimal("33.6907570") >>> xx*2 Decimal("67.3815140") Now, observe what happens when you compare the differences pre-multiplication and post-multiplication: >>> x = Decimal('33.6907570') >>> y = Decimal('33.690756999999998') >>> x - y Decimal("2E-15") >>> x = Decimal('67.3815140') >>> y = Decimal('67.381513999999996') >>> x - y Decimal("4E-15") >>> The discrepancy has carried over and been compounded?and this was a simple multiplication, not something more advanced. Now, while 4e-15 is a relatively small difference, it is a difference that will continue to grow due to the inexact nature of the numbers. This is proof enough that when exact precision is needed, the regular floating point numbers should not be used. *I* need exact numbers?plain and simple. Those are the requirements for the project I am working on, and thus I must adhere to them?and they are non-negotiable, which is why I had opened this thread to begin with. I wanted to know if there was a way to simply switch the default mechanism, that's all. Quite simply, we're talking about a project where the requirements are absolutely zero tolerance for error?and it is clearly evident that Python cannot use a float to store a simple latitude number without causing some error in the precision. And it doesn't take a genius to realize that when you introduce an error?even a minuscule one?into a long sequence of equations, and those equations involve multiplication and division, the error becomes compounded and unpredictable. An example: >>> 1.1 1.1000000000000001 >>> 1.1+0.1 1.2000000000000002 >>> 1.2 1.2 >>> 1.1*100000 110000.00000000001 >>> This does not make any sense at all. Why is 1.1 == 1.1 and some change, and 1.1 + 0.1 is off, but 1.2 is not off on its own? Or, for that matter, why doesn't the default float type recognize that 1.1*100000 = 110000 without any more floating point? It is a whole number. Perhaps you should not make assumptions; I am sure that you have heard what they do at some point before. While *some* of the error doesn't propagate as expected (which is actually a problem in itself?equations no longer make sense if they are not mathematically balanced!) some does. It is unpredictable and can't be tolerated when the numbers must come out exactly. ? Mike -- Michael B. Trausch fd0man at gmail.com Phone: (404) 592-5746 Jabber IM: fd0man at livejournal.com Demand Freedom! Use open and free protocols, standards, and software! -------------- next part -------------- An HTML attachment was scrubbed... URL: From email at christoph-haas.de Fri Nov 24 08:04:23 2006 From: email at christoph-haas.de (Christoph Haas) Date: Fri, 24 Nov 2006 14:04:23 +0100 Subject: Pimping the 'cgi' module In-Reply-To: References: <1164306918.845529.95820@f16g2000cwb.googlegroups.com> Message-ID: <200611241404.23599.email@christoph-haas.de> On Friday 24 November 2006 13:08, robert wrote: > well, note, for that they have named it Ruby-On-Rails, so its still the > language - leveraged. While it is Zope/Django/Ego-on-Python ... ? If by that you mean that neither Zope nor Django are exactly pythonic I think I concur. > Unless a Guido'ed version of such thing is not _selected_ into the > stdlib or at least promoted single-mindedly and prominently by far > before high-tech-but-low-number names like Zope and Django, Python will > continue to bleed out heavily on numbers vs. Ruby. Guido seems to have been confused about the rank growth of web based frameworks himself. So it's even less likely one of them gets included as part of the standard library in finite time. > First need of course: an update of that cgi "module". Oh, yeah. I just joined the Web SIG and found out that WSGI seems the way to go. At a first look it seems horrible if you just want to provide a CGI module. But there must be some reason for its existence. :) Looking further through http://wiki.python.org/moin/WebFrameworks my head starts to spin. Somehow I sadly feel I would just add another incomplete framework to that pile. I'm especially unsure whether it's good or bad to create another "I'm sick of the standard library"-style module. I've just become a bit less confident to actually contribute something useful there. Overwhelming. > python-dev is fully occupied with top-notch inner life. Of course that > is the basis. But key issues in lib&tools were simply forgotten - left > to a random community. Which doesn't match the "batteries included" fuss at all. Of course the basis has to be good, too. And there are so many paradigms today that no core-python developer can really be expected to provide good standard modules for everyone. > Go for a start. In order to realize that essential batteries in good > quality within time - even after 10 years now - it is necessary, to hook > python-dev for even requesting it actively. Just adding to > http://wiki.python.org/moin/WebProgramming and > http://wiki.python.org/moin/WebFrameworks is not the task. It requires > some organization and somewhat a selection process in addition to good > (probably existing) code v0.1xxx material. I think it would not be > overly complex. Both, a new cgi and possibly included snake "rails" (vs > "oil") Oil is deprecated anyway. :) I'll see if I can find my way into the SIG. And - yes - adding another framework will surely not help us out of the divergence. The more frameworks there are the more people seem to feel urged to say "heck, it will be easier to write my own framework than evaluate all 30 packages on that page". Christoph From will at willNOmcguganSPAM.com Thu Nov 23 14:41:13 2006 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Thu, 23 Nov 2006 19:41:13 +0000 Subject: Python 2.5 idle and print command How do I suppress a line feed? In-Reply-To: <1164310576.767673.297470@h54g2000cwb.googlegroups.com> References: <1164310576.767673.297470@h54g2000cwb.googlegroups.com> Message-ID: <4565f93d$0$1493$db0fefd9@news.zen.co.uk> notejam wrote: > Hi, > I am having a problem with print statements always cause a line feed. > I need to print a line of text, then the next print statement will > start printing where the last one stopped rather than drop down a line. > > In basic we can do this with print "texst"; followed by next command > print "text2" > So how do I do that in python? > Thusly... print "texst", print "text2" -- work: http://www.kelpiesoft.com blog: http://www.willmcgugan.com From bearophileHUGS at lycos.com Thu Nov 30 03:20:06 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 30 Nov 2006 00:20:06 -0800 Subject: Remarkable results with psyco and sieve of Eratosthenes In-Reply-To: <1164849303.053474.97990@j72g2000cwa.googlegroups.com> References: <1164837289.295731.178070@h54g2000cwb.googlegroups.com> <456e08ba$0$1505$db0fefd9@news.zen.co.uk> <1164849303.053474.97990@j72g2000cwa.googlegroups.com> Message-ID: <1164874805.870343.21980@j72g2000cwa.googlegroups.com> George Sakkis: > You can also save an attribute lookup for append; just add > append = primes.append > outside of the loop and replace primes.append(x) with append(x) > That should cut down a few fractions of second. We were talking about Psyco, and I think with Psyco (just released for Py 2.5, BTW) such tricks are less useful. Bye, bearophile From jstroud at mbi.ucla.edu Tue Nov 14 19:03:34 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 15 Nov 2006 00:03:34 GMT Subject: refactoring so that multiple changes can be made with one variable? In-Reply-To: <4559e396$0$32430$c3e8da3@news.astraweb.com> References: <4559e396$0$32430$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > My code is below. For now I'm focusing on the lines where health (and > armor) are increased in each character class. Let's say I decided to > change the amount of increase in the future. As it is now, I'd have to > go to each character class and change the number so that each is still > in a good relation to the other (right now: 3, 2, 1; later: perhaps 4, > 3, 2, 1, if I added a new class -- i.e., change Fighter from 3 to 4, > Thief from 2 to 3, in other words increase them all by 1). So instead of > changing each one, is there a simple, clean way of just changing a > single number so that this change is reflected in all classes? Hope that > makes sense. > > > > class Character(object): > def __init__(self, name, strength, dexterity, intelligence): > self.name = name > self.health = 10 > self.armor = self.attack = self.defense = self.magic_attack = \ > self.magic_defense = 0 > self.strength = strength > self.dexterity = dexterity > self.intelligence = intelligence > self.adjust_attributes() > > def adjust_attributes(self): > pass > > > class Fighter(Character): > def adjust_attributes(self): > self.health += 3 > self.armor += 3 > self.attack += 2 > self.defense += 2 > self.strength += 1 > > > class Thief(Character): > def adjust_attributes(self): > self.health += 2 > self.armor += 2 > self.attack += 1 > self.defense += 1 > self.magic_defense += 1 > self.dexterity += 1 > > > class Mage(Character): > def adjust_attributes(self): > self.health += 1 > self.armor += 1 > self.magic_attack += 2 > self.magic_defense += 2 > self.intelligence += 1 The place to do this seems to be in the Character class. class Character(object): _health_base_inc = 1 _armor_base_inc = 1 # etc def __init__(self, name, strength, dexterity, intelligence): self.name = name self.health = 10 self.armor = self.attack = self.defense = self.magic_attack = \ self.magic_defense = 0 self.strength = strength self.dexterity = dexterity self.intelligence = intelligence self.adjust_attributes() def adjust_attributes(self): pass class Mage(Character): # for symmetry with Character _health_char_inc = 1 _armor_char_inc = 1 # etc def adjust_attributes(self): self.health += self._health_char_inc + self_health_base_inc self.armor += self._armor_char_inc + self._armor_base_inc # etc James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From martin at v.loewis.de Thu Nov 16 18:00:08 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 17 Nov 2006 00:00:08 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: References: Message-ID: <455CED78.1060604@v.loewis.de> gabor schrieb: > so basically i'd like to ask here: am i reading something incorrectly? You are reading it correctly. This is how it behaves. > or am i using os.listdir the "wrong way"? how do other people deal with > this? You didn't say why the behavior causes a problem for you - you only explained what the behavior is. Most people use os.listdir in a way like this: for name in os.listdir(path): full = os.path.join(path, name) attrib = os.stat(full) if some-condition: f = open(full) ... All this code will typically work just fine with the current behavior, so people typically don't see any problem. Regards, Martin From Andreas.Ames at comergo.com Mon Nov 13 13:25:03 2006 From: Andreas.Ames at comergo.com (Ames Andreas) Date: Mon, 13 Nov 2006 19:25:03 +0100 Subject: Singleton Class Exception Message-ID: <552B6B925278EF478EA8887D7F9E5AC301816443@tndefr-ws00024.tenovis.corp.lan> > -----Original Message----- > From: python-list-bounces+andreas.ames=comergo.com at python.org > [mailto:python-list-bounces+andreas.ames=comergo.com at python.or > g] On Behalf Of Dan Lenski > Sent: Monday, November 13, 2006 7:05 PM > Subject: Re: Singleton Class Exception > > dischdennis wrote: > > the line "raise Singleton.__single" invokes in my class the > following > > error: > > > > exceptions must be classes, instances, or strings (deprecated), not > > PurchaseRequisitionController > > Denis, > Jason's explanation is correct! You are trying to use the Singleton I don't think so. The op wrote that he uses 2.4.3. So I guess, the problem is, that PurchaseRequisitionController inherits (directly or not) from 'object'. Although new style classes are allowed as exceptions in 2.5, an additional requirement is, that the exception must inherit from BaseException (or must not be a new style class instance at all, as before). cheers, aa -- Andreas Ames | Programmer | Comergo GmbH | Voice: +49 69 7505 3213 | ames AT avaya DOT com From andre.burgaud at gmail.com Thu Nov 23 09:03:31 2006 From: andre.burgaud at gmail.com (Andre Burgaud) Date: Thu, 23 Nov 2006 08:03:31 -0600 Subject: Porting Tkinter application to JYthon In-Reply-To: <1164289006.543874.307110@l12g2000cwl.googlegroups.com> References: <1164289006.543874.307110@l12g2000cwl.googlegroups.com> Message-ID: <158731350611230603v41382941j65adef0550391aa3@mail.gmail.com> Hi Sandip, JPype could be a solution to implement the second option mentioned by Tim: http://jpype.sourceforge.net/ Thanks, Andre http://www.burgaud.com/ On 23 Nov 2006 05:36:46 -0800, Tim N. van der Leeuw wrote: > > Hi, > > sandip desale wrote: > > Dear All, > > > > We have a Tcl/Tk application written using Python 2.2. Using this > application we want to call some customizable Java APIs. I tried porting > Tcl/Tk application to Jython but not able to do the same as TKinter library > is not available with JYthon. > > > > Can you please help me in porting Tkinter application to Jython? Also > kindly let me know how to do the same. > > Not having Tkinter in Jython, you can either rewrite your app to be a > Java Swing app, or you can embed the Java JVM into the Python > interpreter as an importable library. I believe some projects exist to > enable the latter, although I don't know of a URL. > > Cheers, > > --Tim > > > > > > Thanks & Regards, > > Sandip Desale > > > > > > -- > > > > Search for products and services at: > > http://search.mail.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From klaus at seistrup.dk Wed Nov 22 08:18:53 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Wed, 22 Nov 2006 13:18:53 +0000 (UTC) Subject: How to sort list References: <1164136547.137154.126740@m73g2000cwd.googlegroups.com> Message-ID: Fredrik Lundh wrote: > note that DSU is built into Python these days: > > L.sort(key=transform) Sweet, thanks for the hint. Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From cyberco at gmail.com Mon Nov 20 04:58:47 2006 From: cyberco at gmail.com (cyberco) Date: 20 Nov 2006 01:58:47 -0800 Subject: fileinput.input('test.txt') => ERROR: input() already active In-Reply-To: References: <1164011174.630226.91580@j44g2000cwa.googlegroups.com> Message-ID: <1164016727.678036.225640@e3g2000cwe.googlegroups.com> Ah, thanks! Another related question I have: The following piece edits in place, but ads whitelines between all lines of a Windows text file. Why? =========================== fi = fileinput.input('test.txt', inplace=1) for l in fi: print l.replace('a', 'b') =========================== From sjmachin at lexicon.net Fri Nov 24 15:47:18 2006 From: sjmachin at lexicon.net (John Machin) Date: 24 Nov 2006 12:47:18 -0800 Subject: SQLite3__Python2.3-SQLite__Problem In-Reply-To: <1164325325_8617@sp6iad.superfeed.net> References: <1164325325_8617@sp6iad.superfeed.net> Message-ID: <1164401238.582515.226860@45g2000cws.googlegroups.com> Cousin Stanley wrote: > It's been almost 2 years since I've done anything > with Python and SQLite and I'm having some problems > that I don't recall from my last usage .... > > It seems that SQLite3 data bases created at the command line > and those created using the sqlite module from within Python > are no longer compatible with each other using the setup that > I now have .... > > I thought I remembered that the data bases created either way > were always 100% transparent with each other and that I could > use an SQLite3 data base either from the command line or from > within Python without any problems at all .... My guess is that 2 years ago you were using sqlite 2, not 3. > > I did a fair amount of Google-izing looking for related problems > but didn't have much success .... > In that case your googler is absolutely rooted and should be replaced immediately. With mine, google("file is encrypted or is not a database") produces as first hit (would you believe!?) http://wiki.rubyonrails.org/rails/pages/HowtoUseSQLite which contains the text: """ Q: SQLite::Exceptions::\DatabaseException file is encrypted or is not a database. A: It seems that sqlite databases created with version 2 do not work with sqlite version 3 and vice versa. """ IOW sqlite is a candidate for nomination to the "We Could Have Given A Much More Helpful Error Message" Hall of Illfame :-) Alternatively, you could get it straight from the the horse's mouth, at http://www.sqlite.org/version3.html """The format used by SQLite database files has been completely revised. The old version 2.1 format and the new 3.0 format are incompatible with one another. Version 2.8 of SQLite will not read a version 3.0 database files and version 3.0 of SQLite will not read a version 2.8 database file.""" According to http://www.sqlite.org/oldnews.html, the first non-beta version of 3.0 was released in September 2004. You appear to have a 3.2 version of the sqlite3 command-line utility. So far, so good. However, I would be very suspicious of an sqlite that came with Python 2.3 -- it's probably sqlite version 2.something >From your 2nd message: > I'm now off to look for a version of PySQLite2 > that is built for Debian Sarge and Python 2.3 > to see if that might help to rectify the problem .... Sounds like a good idea. Change it to read "that has been built *recently*" and it sounds like an even better idea :-) On Windows, with Python 2.4 (just like your trial): | >>> from pysqlite2 import dbapi2 as DB | >>> DB.version # version of pysqlite2 | '2.3.2' | >>> DB.sqlite_version # This is the one that matters! | '3.3.6' Try extracting sqlite_version from your Linux setup. Aside: with Python 2.5: | >>> import sys; sys.version | '2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]' | >>> import sqlite3; sqlite3.sqlite_version | '3.3.4' # time warp? As you are discovering with Debian, one of the downsides of having 3rd-party goodies bundled in instead of downloading and installing them yourself is that thay can become frozen in time -- not quite as bad as the ruins of Pompeii; although Python 2.3 is getting close :-) HTH, John From dandolls at yahoo.co.in Fri Nov 24 15:16:50 2006 From: dandolls at yahoo.co.in (amit saha) Date: Sat, 25 Nov 2006 01:46:50 +0530 (IST) Subject: Python on your mobile phone Message-ID: <20061124201650.48035.qmail@web7613.mail.in.yahoo.com> Hi list! The most exciting thing that i am doing offlate has been this. I am programming on my mobile using my new favourite language, Python. Though this thing might not be new to many of you, but then i am a late starter. And i was completely ignorant of this before partly because i did not have the "proper" phone and also i never thought of Python so seriously as i do now. This article will serve a dual purpose. Those of you ignorant of Python will start appreciating this simple,elegant and powerful language and also make you start doing more with your mobile phone. For me, it is something which will keep me busy everywhere now, during journeys, during boring class hours,during power cuts and every single second which used to be wasted earlier. Access the full text here. http://geocities.com/amit_saha_works/python/python-s60.html Amit Saha *A Proud Ubuntero* http://amitsaha.in.googlepages.com __________________________________________________________ Yahoo! India Answers: Share what you know. Learn something new http://in.answers.yahoo.com/ From python-url at phaseit.net Mon Nov 20 18:22:51 2006 From: python-url at phaseit.net (Paul Boddie) Date: Mon, 20 Nov 2006 23:22:51 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Nov 20) Message-ID: QOTW: "I think you've got the wrong intuition about the balance between the amount of bandwidth and the amount of computation a given numer [sic] of dollars would buy. You've hundreds of CPU cycles available per bit transmitted; space enough to stick in even Python." - Thomas Womack (on comp.lang.lisp, earlier this year, so it's not a true QOTW) http://groups.google.com/group/comp.lang.lisp/msg/453239d7b8e0ef72 "I'm a recent, belated convert from Perl. I work in a physics lab and have been using Python to automate a lot of measurement equipment lately. It works fabulously for this purpose." - Dan Lenski On the subject of Python and large volumes of data, it would seem that maps and data visualisation are a natural combination for the pydap treatment: http://taoetc.org/27 "MIT to try Python ...": http://www.amk.ca/diary/2006/11/mit_to_try_python_for_introduc.html A treatment of many different domains can be found in the itools package (and the 21 subpackages of the 0.14.5 release!): http://groups.google.com/group/comp.lang.python.announce/browse_frm/thread/4f0480456bfac121/ http://www.ikaaro.org/itools Problems with Python 2.5 portability? Or, more precisely, with extension modules not working with the new release? http://mail.python.org/pipermail/python-dev/2006-November/069967.html BaseHTTPRequestHandler accesses POST data through rfile: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c928f2ab0f5c1e63/ pyparsing and itertools: wise coders ready to move past RE know 'em both: http://groups.google.com/group/comp.lang.python/browse_thread/thread/85646f5cbd7e0718/ Is comparing Python and PHP a "fair comparison"? The debate focuses on many things that make languages popular for Web applications: http://groups.google.com/group/comp.lang.python/browse_frm/thread/4156e7f6d5a90c84/ The big news outside the Python community last week was the surprising GPL-licensing of many of Sun's Java technologies. So, will GPL-licensed Java eat into Python's market share? http://groups.google.com/group/comp.lang.python/browse_frm/thread/e52bf7ac89325485/ All these comparisons whet the appetite for some real advocacy, coordinated by the Python Software Foundation's own man: http://groups.google.com/group/comp.lang.python.announce/browse_frm/thread/c71513d3fbed25ef/ Advocacy applies at all levels, of course, backed up by comparisons, tests, benchmarks... In the Web opinions shootout it's TurboGears vs. Django: http://groups.google.com/group/turbogears/browse_frm/thread/a37037677b067872 And Django vs. Rails: http://groups.google.com/group/django-users/msg/328151a262c00eb0 The conflict (good natured, of course) extends to literature as the TurboGears book hits the shelves: http://groups.google.com/group/turbogears/msg/318bfff14bcf0ef3 Whilst the Django book - still a work in progress - is readable in its evolving form: http://www.djangobook.com Decide between the Web programming options yourself, but without really installing anything. Be prepared for quite a choice, as noted by a Django lead developer on the TurboGears discussion group! http://www.vmware.com/vmtn/appliances/directory/289 And even if you're a disinterested observer, the battle of these big frameworks still provides benefits to those just looking for decent Web hosting (and bringing us full circle to that PHP vs. Python discussion): http://groups.google.com/group/comp.lang.python/browse_frm/thread/17718e04ab4a6e25/ Secure Python: is running untrusted code a good idea, and is it Python or the operating system who can offer the most help? http://groups.google.com/group/comp.lang.python/browse_frm/thread/fb27c42ee21afcaf/ And what about "untrusted" contributors to your blog's comments. There's SpamBayes for e-mail, but can one filter blog comments in the same way? http://www.larsen-b.com/Article/244.html As people continually note, as CPython motors onward with many new features, Jython struggles to keep up. Could the biggest motivational force behind its revival really be the principal developer of JRuby? http://headius.blogspot.com/2006/11/jython-alive-and-well-and-looking-for.html But don't start to think that old releases of Python don't see any action. Here, Python 1.5.2 makes an appearance on Telit's GSM/GPRS telecoms/networking modules: http://www.telit.co.it/modules.asp?lang=1 ======================================================================== 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, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html 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/python/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 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-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From __peter__ at web.de Tue Nov 28 04:55:15 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Nov 2006 10:55:15 +0100 Subject: How to increase the speed of this program? References: <1164699156.682944.97410@j44g2000cwa.googlegroups.com> <1164706548.778583.267730@n67g2000cwd.googlegroups.com> Message-ID: Peter Otten wrote: > Leo Kislov wrote: > >> >> Peter Otten wrote: >>> Peter Otten wrote: >>> >>> > HYRY wrote: >>> > >>> >> I want to join two mono wave file to a stereo wave file by only using >>> >> the default python module. >>> >> Here is my program, but it is much slower than the C version, so how >>> >> can I increase the speed? >>> >> I think the problem is at line #1, #2, #3. >>> > >>> >> oarray = array.array("h", [0]*(len(larray)+len(rarray))) #1 >>> > >>> > ITEMSIZE = 2 >>> > size = ITEMSIZE*(len(larray) + len(rarray)) >>> > oarray = array.array("h") >>> > oarray.fromstring("\0" * size) >>> > >>> > may be a bit faster. >>> >>> Confirmed: >>> >>> $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = >>> array("h"); a.fromstring("\0"*(2*N))' >>> 100 loops, best of 3: 9.68 msec per loop >>> $ python2.5 -m timeit -s'from array import array; N = 10**6' 'a = >>> array("h", >>> [0]*N);' >>> 10 loops, best of 3: 199 msec per loop >> >> Funny thing is that using huge temporary string is faster that >> multiplying small array: >> >> C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a >> =array('h'); a.fromstring('\0'*(2*N))" >> 100 loops, best of 3: 9.57 msec per loop >> >> C:\Python25>python -m timeit -s"from array import array; N = 10**6" "a >> = array('h','\0\0'); a*N" >> 10 loops, best of 3: 28.4 msec per loop >> >> Perhaps if array multiplication was as smart as string multiplication >> then array multiplication version would be the fastest. Oops, I have to work on my reading skills. You're right, of course... > That will not suffice: > > $ python2.5 -m timeit -s'from array import array; from itertools import > repeat; N = 10**6; init = [0]*N' 'array("h", init)' > 10 loops, best of 3: 130 msec per loop > > $ python2.5 -m timeit -s'from array import array; from itertools import > repeat; N = 10**6; init = "\n"*(2*N)' 'array("h").fromstring(init)' > 100 loops, best of 3: 5 msec per loop > > A big chunk of the time is probably consumed by "casting" the list items. > Perhaps an array.fill(value, repeat) method would be useful. ... and that could be spelled array.__mul__ as you suggest. Peter From Jeff.Demel at JavelinDirect.com Tue Nov 21 16:10:32 2006 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Tue, 21 Nov 2006 15:10:32 -0600 Subject: Psycopg2 | collapse row to string Message-ID: <136ED738BD4F1545B97E4AC06FF6370734BFFC@DMSP-MSG-EVS01.mail.pvt> I'm pulling some records from a database using psycopg2, then looping through the rows to do some data checking and then writing the results to a file if they pass some integrity checks. Simple enough, but... Is there an easy want to create a delimited string from this, for example: for row in rows: if checksomething == 100: newline = row[].combine("delimiter of some kind") resultfile.write(newline) Obviously, the "row[].combine(delimeter)" is what I'm hoping exists. TIA -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From vedran at v-programs.com Thu Nov 30 12:35:18 2006 From: vedran at v-programs.com (Croteam) Date: 30 Nov 2006 09:35:18 -0800 Subject: shtoom making PC2Phone calls Message-ID: <1164908118.401178.201670@80g2000cwy.googlegroups.com> Hello, Can somebody give me shtoom examples or source code for making PC2Phone calls and pc to pc calls. (if you give me source code,please give me full url to that source or send me to email: vedran at v-programs.com) Thanks,I will really appreciate that From steve at rueb.com Thu Nov 30 10:38:21 2006 From: steve at rueb.com (Steve Bergman) Date: 30 Nov 2006 07:38:21 -0800 Subject: why would anyone use python when java is there? In-Reply-To: <1164874749.914101.32410@16g2000cwy.googlegroups.com> References: <1164762232.220759.57160@h54g2000cwb.googlegroups.com> <1164764454.043697.125730@j72g2000cwa.googlegroups.com> <1164874749.914101.32410@16g2000cwy.googlegroups.com> Message-ID: <1164901101.117456.89080@n67g2000cwd.googlegroups.com> Bruce Eckel states the case pretty well in this interview: http://www.artima.com/intv/aboutme.html Bruce is the author of "Thinking In Java" and other excellent books, but has migrated from the Java camp. (I'm excited to see him getting at least a bit involved in TurboGears. He has a lot to offer any project in which he takes an interest.) I find his opinions particularly relevant. I've tried doing the Java thing, mainly because of the hype surrounding it... and the marketability. But I never got very far because I just disliked the language. (Personal opinion. But hey, this *is* comp.lang.python!) From timr at probo.com Thu Nov 23 16:57:12 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 23 Nov 2006 21:57:12 GMT Subject: len(var) is [CONSTANT] equal to len(var) == [CONSTANT]? References: Message-ID: <446cm2pusjhvnkr7515qeoh2p44aasdgjl@4ax.com> Tor Erik Soenvisen wrote: > >(len(['']) is 1) == (len(['']) == 1) => True > >Is this the case for all numbers? I've tried running the following: > >for i in range(10000): > for j in range(10000): > if i != j: > assert id(i) != id(j), 'i=%d, j=%d, id=%d' % (i, j, id >(i)) > >which executes fine. Hence, 0-9999 is okey... But this is a relatively >small range, and sooner or later you probably get two numbers with the same >id... Thoughts anyone? It has been my experience that virtually every use of the "is" operator (except "is None") is wrong. Now, I fully understand that there are perfectly valid uses for "is", and the standard library contains a few, but for the non-guru casual Python programmer, I think it is safe to say "never use 'is'". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From no-spam at no-spam-no-spam.invalid Tue Nov 28 05:51:34 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Tue, 28 Nov 2006 11:51:34 +0100 Subject: HTML Table-of-Content Extraction Script Message-ID: I'm looking for a function which extracts a table of contents of HTML file(s) from
... and possibly auto-creates the ancors. Maybe something already exists? Robert From aahz at pythoncraft.com Thu Nov 23 10:21:27 2006 From: aahz at pythoncraft.com (Aahz) Date: 23 Nov 2006 07:21:27 -0800 Subject: Trying to understand Python objects References: <1164150237.709846.38790@e3g2000cwe.googlegroups.com> <45643a6f$0$7761$426a74cc@news.free.fr> <1164206156.302934.183510@b28g2000cwb.googlegroups.com> Message-ID: In article <1164206156.302934.183510 at b28g2000cwb.googlegroups.com>, walterbyrd wrote: > >Is there some book, or other reference, that explains of this? I was >thinking about "Python for Dummies." The "Think like a Computer >Scientist" book, and "Dive into Python" book don't seem to explain >Python's object model clearly enough for me. Speaking as the co-author of _Python for Dummies_, we certainly tried to make much of this clear, but I haven't seen any reviews yet (partly our fault for not getting out review copies). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 1993 From steve at REMOVEME.cybersource.com.au Wed Nov 15 02:57:39 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 15 Nov 2006 18:57:39 +1100 Subject: refactoring so that multiple changes can be made with one variable? References: <4559e396$0$32430$c3e8da3@news.astraweb.com> Message-ID: On Tue, 14 Nov 2006 10:41:53 -0500, John Salerno wrote: > My code is below. For now I'm focusing on the lines where health (and > armor) are increased in each character class. Let's say I decided to > change the amount of increase in the future. As it is now, I'd have to > go to each character class and change the number so that each is still > in a good relation to the other (right now: 3, 2, 1; later: perhaps 4, > 3, 2, 1, if I added a new class -- i.e., change Fighter from 3 to 4, > Thief from 2 to 3, in other words increase them all by 1). So instead of > changing each one, is there a simple, clean way of just changing a > single number so that this change is reflected in all classes? Hope that > makes sense. Cutting your code down to the minimum that exhibits the behaviour you want: class Character(object): def __init__(self, name, strength, dexterity, intelligence): self.name = name self.health = 10 # and so on... self.adjust_attributes() def adjust_attributes(self): pass class Fighter(Character): def adjust_attributes(self): self.health += 3 class Thief(Character): def adjust_attributes(self): self.health += 2 etc. Sounds like you want some sort of factory function that returns a class: # WARNING: untested def make_character_class(name, adjustments): class klass(Character): _adjustments = {} def adjust_attributes(self): for key, value in self._adjustments.items(): x = getattr(self, key) setattr(self, key, x + item) setattr(klass, klass.__name__, name) setattr(klass, klass._adjustments, adjustments) return klass And now you use it like this: Fighter = make_character_class('Fighter', {'health': 3}) Thief = make_character_class('Thief', {'health': 2}) Now you can easily change the adjustments, all in just a few lines. Here's another idea: character_adjustments = { 'Fighter': {'health': 3}, 'Thief': {'health': 2}, 'Mage': {'intelligence': 3, 'strength': -1} } and change the make_character_class factory function above to only take a single argument, name. Now if you decide you want to *programmatically* adjust the adjustments, you can do this: # still untested... for key in character_adjustments: for attribute, value in key.items(): # adjust the values to make up for my poor choices character_adjustments[key][attribute] = value + 1 (but of course you must do this BEFORE creating your character classes!) And last but most certainly not least, you can separate the adjustment values into (say) an INI file, read them in at run-time and pass those values to the factory function above. Then write another function which walks through the INI file, adjusting the values in place as needed. This is obviously going to take the most work, so I strongly suggest you don't go down this path unless you really have to. -- Steven D'Aprano From bbands at gmail.com Thu Nov 30 14:58:24 2006 From: bbands at gmail.com (BBands) Date: 30 Nov 2006 11:58:24 -0800 Subject: DDE (eSignal) In-Reply-To: References: <1164912970.711046.214060@80g2000cwy.googlegroups.com> Message-ID: <1164916703.978005.63070@l12g2000cwl.googlegroups.com> Thomas Heller wrote: > Looks like a bug, either in the dde module or the dde server. > But it's easy to find a workaround: > '1402.670000000000\x00\x12\x00*\x00\x00\x004\xfb\x12\x00\xfd\x1a\xd9w4\xc1\x00'.split("\0")[0] > '1402.670000000000' float(last.split("\0")[0]) works for me. Thanks for that! jab From robin at alldunn.com Wed Nov 8 02:59:14 2006 From: robin at alldunn.com (Robin Dunn) Date: Tue, 07 Nov 2006 23:59:14 -0800 Subject: ANN: wxPython 2.7.2.0 Message-ID: <45518E52.4010306@alldunn.com> Announcing ---------- The 2.7.2.0 release of wxPython is now available for download at http://wxpython.org/download.php. This is expected to be the last stepping stone in the path to the next stable release series, 2.8.x. We're pushing full speed ahead in order to get 2.8.0 included with OSX 10.5, and so far we are very close to being on schedule. This release has some house-keeping style changes, as well as some user-contributed patches and also the usual crop of bug fixes. Source and binaries are available for both Python 2.4 and 2.5 for Windows and Mac, as well some pacakges for varous 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. Changes in 2.7.2.0 ------------------ Patch [ 1583183 ] Fixes printing/print preview inconsistencies Add events API to wxHtmlWindow (patch #1504493 by Francesco Montorsi) Added wxTB_RIGHT style for right-aligned toolbars (Igor Korot) Added New Zealand NZST and NZDT timezone support to wx.DateTime. wx.Window.GetAdjustedBestSize is deprecated. In every conceivable scenario GetEffectiveMinSize is probably what you want to use instead. wx.Image: Gained support for TGA image file format. wx.aui: The classes in the wx.aui module have been renamed to be more consistent with each other, and make it easier to recognize in the docs and etc. that they belong together. FrameManager --> AuiManager FrameManagerEvent --> AuiManagerEvent PaneInfo --> AuiPaneInfo FloatingPane --> AuiFloatingPane DockArt --> AuiDockArt TabArt --> AuiTabArt AuiMultiNotebook --> AuiNotebook AuiNotebookEvent --> AuiNotebookEvent wx.lib.customtreectrl: A patch from Frame Niessink which adds an additional style (TR_AUTO_CHECK_PARENT) that (un)checks a parent when all children are (un)checked. wx.animate.AnimationCtrl fixed to display inactive bitmap at start (patch 1590192) Patch from Dj Gilcrease adding the FNB_HIDE_ON_SINGLE_TAB style flag for wx.lib.flatnotebook. wx.Window.GetBestFittingSize has been renamed to GetEffectiveMinSize. SetBestFittingSize has been renamed to SetInitialSize, since it is most often used only to set the initial (and minimal) size of a widget. The QuickTime backend for wx.media.MediaCtrl on MS Windows works again. Just pass szBackend=wx.media.MEDIABACKEND_QUICKTIME to the constructor to use it instead of the default ActiveMovie backend, (assuming the quicktime DLLs are available on the system.) -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From mauriceling at acm.org Wed Nov 15 17:41:19 2006 From: mauriceling at acm.org (Maurice LING) Date: Wed, 15 Nov 2006 22:41:19 GMT Subject: Will GPL Java eat into Python marketshare? In-Reply-To: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> References: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> Message-ID: <455b978c$1@news.unimelb.edu.au> walterbyrd wrote: > Some think it will. > > Up untill now, Java has never been standard across different versions > of Linux and Unix. Some think that is one reason that some developers > have avoided Java in favor of Python. Now that Java has been GPL'd that > might change. > > IMO: it won't make much difference. But I don't really know. > I'm hoping for a more optimistic outcome that this may open a possibility for tigher interoperability between java programs and python programs. That is, run java class files or java codes natively on python VM. Is this still a blue sky dream? maurice From arkanes at gmail.com Mon Nov 27 13:53:24 2006 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 27 Nov 2006 12:53:24 -0600 Subject: super() and type() Message-ID: <4866bea60611271053s2875daaen5292c94cdd0ef04e@mail.gmail.com> I see super documented, and in use, as below (from the Python documentation) class C(B): def meth(self, arg): super(C, self).meth(arg) I'd like to not write C all the time, so is there any problem with writing: class C(B): def meth(self, arg): super(type(self), self).meth(arg) This seems to work in practice but I don't see it used anywhere and I'm worried what I might be missing. This was especially brought to my attention because pylint flags the second usage as invalid, and I'm not sure if it should be considered a false positive or not. From no-spam at no-spam-no-spam.invalid Wed Nov 15 08:56:18 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 15 Nov 2006 14:56:18 +0100 Subject: numpy/scipy: error of correlation coefficient (clumpy data) In-Reply-To: <1163373385.596233.102100@k70g2000cwa.googlegroups.com> References: <1163351475.742836.311180@h48g2000cwc.googlegroups.com> <1163373385.596233.102100@k70g2000cwa.googlegroups.com> Message-ID: sturlamolden wrote: > robert wrote: > >>> t = r * sqrt( (n-2)/(1-r**2) ) > >> yet too lazy/practical for digging these things from there. You obviously got it - out of that, what would be a final estimate for an error range of r (n big) ? >> that same "const. * (1-r**2)/sqrt(n)" which I found in that other document ? > > I gave you th formula. Solve for r and you get the confidence interval. > You will need to use the inverse cumulative Student t distribution. > > Another quick-and-dirty solution is to use bootstrapping. > > from numpy import mean, std, sum, sqrt, sort > from numpy.random import randint > > def bootstrap_correlation(x,y): > idx = randint(len(x),size=(1000,len(x))) > bx = x[idx] # reasmples x with replacement > by = y[idx] # resamples y with replacement > mx = mean(bx,1) > my = mean(by,1) > sx = std(bx,1) > sy = std(by,1) > r = sort(sum( (bx - mx.repeat(len(x),0).reshape(bx.shape)) * > (by - my.repeat(len(y),0).reshape(by.shape)), 1) / > ((len(x)-1)*sx*sy)) > #bootstrap confidence interval (NB! biased) > return (r[25],r[975]) > > >> My main concern is, how to respect the fact, that the (x,y) points may not distribute well along the regression line. > > The bootstrap is "non-parametric" in the sense that it is distribution > free. thanks for the bootstrap tester. It confirms mainly the "r_stderr = (1-r**2)/sqrt(n)" formula. The assymetry of r (-1..+1) is less a problem. Yet my main problem, how to respect clumpy distribution in the data points, is still the same. In practice think of a situation where data out of an experiment has an unkown damping/filter (or whatever unkown data clumper) on it, thus lots of redundancy in effect. An extreme example is to just duplicate data: >>> x ,y =[0.,0,0,0,1]*10 ,[0.,1,1,1,1]*10 >>> xx,yy=[0.,0,0,0,1]*100,[0.,1,1,1,1]*100 >>> correlation(x,y) (0.25, 0.132582521472, 0.25, 0.75) >>> correlation(xx,yy) (0.25, 0.0419262745781, 0.25, 0.75) >>> bootstrap_correlation(array(x),array(y)) (0.148447544378, 0.375391432338) >>> bootstrap_correlation(array(xx),array(yy)) (0.215668822617, 0.285633303438) >>> here the bootstrap test will as well tell us, that the confidence intervall narrows down by a factor ~sqrt(10) - just the same as if there would be 10-fold more of well distributed "new" data. Thus this kind of error estimation has no reasonable basis for data which is not very good. The interesting task is probably this: to check for linear correlation but "weight clumping of data" somehow for the error estimation. So far I can only think of kind of geometric density approach... Or is there a commonly known straight forward approach/formula for this problem? In this formula which I can remember weakly somehow - I think there were other basic sum terms like sum_xxy, sum_xyy,.. in it (which are not needed for the formula for r itself ) Robert From cemerick at snowtide.com Sat Nov 18 12:40:05 2006 From: cemerick at snowtide.com (Chas Emerick) Date: Sat, 18 Nov 2006 12:40:05 -0500 Subject: lxml/ElementTree and .tail In-Reply-To: References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> <761846B7-E374-41FE-8804-CBB3D42FD4D2@snowtide.com> <1163835505.102190.140060@b28g2000cwb.googlegroups.com> <894503B9-B571-42E3-9FA0-B0C67D333A3D@snowtide.com> Message-ID: On Nov 18, 2006, at 11:29 AM, Fredrik Lundh wrote: > Chas Emerick wrote: > >>> and keep patting our- >>> selves on the back, while the rest of the world is busy routing >>> around >>> us, switching to well-understood XML subsets or other serialization >>> formats, simpler and more flexible data models, simpler API:s, and >>> more robust code. and Python ;-) >> >> That's flatly unrealistic. If you'll remember, I'm not one of "those >> people" that are specification-driven -- I hadn't even *heard* of >> Infoset until earlier this week! > > The rant wasn't directed at you or anyone special, but I don't really > think you got the point of it either. Which is a bit strange, because > it sounded like you *were* working on extracting information from > messy > documents, so the "it's about the data, dammit" way of thinking > shouldn't be news to you. No, it's not any kind of news at all, and I'm very sympathetic to your specific perspective (and have advocated it in other contexts and circumstances, where appropriate). And yes, we are in fact ensuring that we get from the HTML/XHTML/text/PDF/etc serialization we have to consume to a uniform, normalized, and "clean" data model in as few steps as possible. However, in those few steps, we have to recognize the functional reality of how each data representation is used out in the world in order to translate it into a uniform model for our own purposes. In concrete terms, that means that an end tag in an XHTML serialization means that that element is closed, done, finit. Any other representation of that serialization doesn't correspond properly with the intent of that HTML document's author. > And the routing around is not unrealistic, it's is a *fact*; JSON and > POX are killing the full XML/Schema/SOAP stack for communication, > XHTML > is pretty much dead as a wire format, people are apologizing in public > for their use of SOAP, AJAX is quickly turning into AJAJ, few people > care about the more obscure details of the XML 1.0 standard (when did > you last see a conditional section? or even a DTD?), dealing with huge > XML data sets is still extremely hard compared to just uploading the > darn thing to a database and doing the crunching in SQL, and nobody > uses > XML 1.1 for anything. > > Practicality beats purity, and the Internet routes around damage, > every > single time. I agree 100% -- but I would have thought that that's a point I would have made. The model that ET uses seems like a "purified" representation of a mixed-content serialization, exactly because it is geared to an ideal rather than the practical realities of mixed content and expectations thereof. For what it's worth, our current effort is directed towards providing significant stores/feeds of XML/PDF/HTML/text/etc in something that can be dropped into a RDBMS. Perhaps that's the source of the impedance between us: you view Infoset as a functional replacement for serialization-dependent XML, whereas we are focussed on what could be broadly described as a translation from one to the other. >> overwhelming majority of the developers out there care for nothing >> but the serialization, simply because that's how one plays nicely >> with others. > > The problem is if you only stare at the serialization, your code > *won't* > play nicely with others. At the serialization level, it's easy to > think > that CDATA sections are different from other text, that character > references are different from ordinary characters, that you should > somehow be able to distinguish between and , that > namespace prefixes are more important than the namespace URI, that an >   in an XHTML-style stream is different from a U+00A0 > character in > memory, and so on. In my experience, serialization-only thinking (at > the receiving end) is the single most common cause for > interoperability > problems when it comes to general XML interchange. I agree with all of that. I would again refer to the pervasive view of what end tags mean -- that's what I was primarily referring to with the term 'serialization'. > (By the way, did ET fail to *read* your XML documents? I thought your > complaint was that it didn't put the things it read in a place > where you > expected them to be, and that you didn't have time to learn how to > deal > with that because you had more important things to do, at the time?) No, it doesn't put things in the right places, so I consider that a failure of the model. I don't see why I should have spent time learning how to deal with that when another very comprehensive library is available that does meet expectations. *shrug* Further, the fact that ET/lxml works the way that it does makes me think that there may be some other landmines in the underlying model that we might not have discovered until some days, weeks, etc., had passed, so there's a much greater comfort level in working with a library that explicitly supports the model that we expect (and was assumed when the HTML [now XHTML] documents in question were authored). - Chas From carsten at uniqsys.com Thu Nov 16 11:18:14 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 16 Nov 2006 11:18:14 -0500 Subject: Yield In-Reply-To: <1163691173.737911.130410@i42g2000cwa.googlegroups.com> References: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> <455b4f9f$1@usenet01.boi.hp.com> <1163659530.752607.120880@m73g2000cwd.googlegroups.com> <455c15ca$1@news.eftel.com> <455c1ddf@news.eftel.com> <1163691173.737911.130410@i42g2000cwa.googlegroups.com> Message-ID: <1163693894.3380.14.camel@dot.uniqsys.com> On Thu, 2006-11-16 at 07:32 -0800, Danny Colligan wrote: > Carsten mentioned that generators are more memory-efficient to use when > dealing with large numbers of objects. Is this the main advantage of > using generators? Also, in what other novel ways are generators used > that are clearly superior to alternatives? The memory efficiency is definitely a major advantage. Generators allow you to efficiently produce, manipulate, and consume sequences of arbitrary length. The length of the sequence could even be potentially infinite, which is impossible to handle when you're working with actual lists. The memory efficiency aside, it's more elegant to write something like this: def squares(n): for i in range(n): yield i**2 than something like this: def squares(n): result = [] for i in range(n): result.append(i**2) return result -Carsten From michael at stroeder.com Thu Nov 16 08:50:04 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 16 Nov 2006 14:50:04 +0100 Subject: python-ldap and Python 2.5 In-Reply-To: <4555132f$0$3586$9b622d9e@news.freenet.de> References: <4555132f$0$3586$9b622d9e@news.freenet.de> Message-ID: Michael Str?der wrote: > > But this seems to help (tested on my local system): > http://sourceforge.net/tracker/index.php?func=detail&aid=1575329&group_id=2072&atid=102072 Released python-ldap 2.2.1 yesterday which contains this fix. Ciao, Michael. From researchbase at gmail.com Thu Nov 16 13:14:23 2006 From: researchbase at gmail.com (krishnakant Mane) Date: Thu, 16 Nov 2006 23:44:23 +0530 Subject: python and accessibility issues. Message-ID: this question is streight forward, short and sweet. I am developing some applications and being blind myself, expect that including me, all other blind people must be able to use it. so my question is, is wx python complying with Microsoft Active Accessibility or MSAA for short? I will use wx python or any other gui library that is having support for MSAA built in. thanking all. Krishnakant. From fredrik at pythonware.com Wed Nov 15 16:31:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Nov 2006 22:31:26 +0100 Subject: Python-2.5.exe? In-Reply-To: <455b824d$0$7054$c3e8da3@news.astraweb.com> References: <455b824d$0$7054$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: >> python doesn't depend on the registry settings for normal use, so >> you can simply install python as usual, copy python25.dll from >> c:\windows\system32 to c:\python25, and then copy (or move) the >> entire c:\python25 tree to your USB drive. > > Is it safe to assume that if you do this, Python first looks in > C:\Python25 for the dll file, before trying to find the non-existent (on > the USB drive) C:\Windows\System32? Python looks for a DLL in the same directory as the EXE before it looks anywhere else (this is standard Windows behaviour). From python.list at tim.thechases.com Tue Nov 28 06:18:18 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 28 Nov 2006 05:18:18 -0600 Subject: Modifying every alternate element of a sequence In-Reply-To: <1164710289.544394.101170@h54g2000cwb.googlegroups.com> References: <1164710289.544394.101170@h54g2000cwb.googlegroups.com> Message-ID: <456C1AFA.7010304@tim.thechases.com> > I have a list of numbers and I want to build another list with every > second element multiplied by -1. > > input = [1,2,3,4,5,6] > wanted = [1,-2,3,-4,5,-6] > > I can implement it like this: > > input = range(3,12) > wanted = [] > for (i,v) in enumerate(input): > if i%2 == 0: > wanted.append(v) > else: > wanted.append(-v) >>> input = range(3,12) >>> [i%2==0 and v or -v for (i,v) in enumerate(input)] [3, -4, 5, -6, 7, -8, 9, -10, 11] > But is there any other better way to do this. I'm not sure densely packing it into a list comprehension is necessarily a *better* way, just a more compact way. To make more sense of it, you might create a helper function that does your comparison work: def inv_if(v, test): if test: return v else: return -v [inv_if(v, i%2==0) for (i,v) in enumerate(input)] Or you could even do something like def inv_alternating(t): i, v = t if i%2==0: return v else: return -v [inv_alternating(t) for t in enumerate(input)] Either compacts it for the actual call within a list comprehension, but it is cleaner to read what's going on. -tkc From antoine at vo.lu Wed Nov 8 06:49:23 2006 From: antoine at vo.lu (Antoine De Groote) Date: Wed, 08 Nov 2006 12:49:23 +0100 Subject: for x in... x remains global Message-ID: for x in range(3): pass After this statement is executed x is global variable. This seems very unnatural to me and caused me 3 three days of debugging because I was unintentionally using x further down in my program (typo). I would have thought that variables like this are local to the for block. Is there a reason this is not the case? Maybe there are PEPs or something else about the matter that you can point me to? Regards, antoine From spedrosa at gmail.com Mon Nov 13 15:27:42 2006 From: spedrosa at gmail.com (Stephen Eilert) Date: 13 Nov 2006 12:27:42 -0800 Subject: Is python for me? References: <1163437873.721254.31070@b28g2000cwb.googlegroups.com> <1163441468.081643.189600@f16g2000cwb.googlegroups.com> <1163448523.712403.232970@i42g2000cwa.googlegroups.com> Message-ID: <1163449662.186813.52000@k70g2000cwa.googlegroups.com> Not to be picky, but any slowness in software is rarely because of code size. Rather, it is the data size and algorithms that play the major role. Only after you got the first two right is that you should worry about implementation speed. That said, you are correct. Only if you intend to do *heavy* processing of the returned data, your major bottleneck should be the database. *If* you find Python to be slow(for some specific operation, never for a whole application), you could always rewrite that section using another language (C/C++ come to mind), or call external libraries to do the heavy-lifting. The easy integration between Python and C (compared to a couple other popular platforms) is what drove me to Python. Make it work first. Then optimize. And Python helps both. Stephen lennart escreveu: > dakman at gmail.com schreef: > > > As stated above python is capable of all those things, however on > > larger applications like that it can tend to slow down a bit. And the > > executables do need a little bit of work, because it's bassicly a dll > > and a library of all your .pyc files. However python is still a great > > language and I would recomend it. And most of these things will > > probably be fixed in Python 3000! > >> > >> <> > > > Python very quickly. > > Can you define 'large'? Is that large in code, or large in database? I > don't know which database is supported. If its a external db, like > MySql, the query is performed through the software of MySql, am I > right? If I'm correct, the 'slowness' comes from the amount of code in > python itself, not from the database. From tleeuwenburg at gmail.com Sun Nov 26 17:51:10 2006 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 26 Nov 2006 14:51:10 -0800 Subject: The Python Papers License Discussion Message-ID: <1164581470.701666.158880@45g2000cws.googlegroups.com> Thank you all who have commented on the licensing issues surrounding The Python Papers. For the time being, the board and I have decided to continue using the Creative Commons Noncommercial, Attribution and Share-Alike license as the standard license for articles contained in The Python Papers. However, a number of reasonable concerns have been raised by individuals on this forum, the most important I consider to be: * Incompatibility with the Python license, preventing content in The Python Papers from being fed back and redistributed, e.g., with the Python documentation * Possible confusion arising from the slogan "free as in freedom" On that basis, I would like to make two announcements: 1) Authors submitting to The Python Papers will be permitted to choose from a number of licenses for redistributing their work. (note -- their copyright agreement with The Python Papers is *separate* from the copyright agreement they choose to attach for general use). This will allow authors to choose greater freedoms to the re-use of their works if they wish. 2) The Python Papers will no longer use the slogin "free as in freedom" but will adopt the Creative Commons slogan "some rights reserved" in future communications, to the extent possible under human fallibility :) Those who have made comments here might wish to submit them for publication if they would like them to be heard by The Python Papers general readership. This may be done by emailing submissions at pythonpapers.org. We may not publish all submitted comments, and reserve the right to publish them under the license adopted by The Python Papers generally. From bj_666 at gmx.net Sun Nov 26 07:24:21 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 26 Nov 2006 13:24:21 +0100 Subject: Persistent Threads & Synchronisation References: Message-ID: In , Matthew Tylee Atkinson wrote: > They way I want it to work is this: The downloading thread, when > spawned, stays alive for the duration of the program. Occasionally the > main program will call a function in it to download the data and save it > as files on disk. Then, these files are loaded by the main thread. > When this has happened, the main thread calls another function in the > download thread to delete the temporary files. The same thing happens > next time a download is needed, when the user is looking at some other > content. > > My problem is this: the downloading thread only seems to execute code > in a separate thread as long as the run() function (called by the > start() function) is running. This is as per the documentation, of > course. I am performing the download in the run() function, but the > file cleanup is still done with a separate call. This actually does > work, after the download is over, and run() has terminated, but I > believe it isn't happening in a separate thread anymore (as previously I > made a mistake and called run() directly, instead of start() and it > blocked the main program). There seems to be a misunderstanding of threads. You don't call functions in a thread from the main program. If you call a function from the main thread then the function is executed in the main thread. That's true for any call on `Thread` objects except for `start()` which really starts executing the `run()` method in a separate thread. The easiest way for safe communication with threads is a `Queue` like the one in the `Queue` module. If you want a download thread that is running alongside the main program all the time then write a while loop that gets "commands" via a queue. Something like: def run(self): while True: command = self.queue.get() if command == 'exit': break # ... def exit(self): self.queue.put('exit') # ... Of course the `command` objects can be more complex than strings to hold arguments for the worker thread. > I did wonder about using a Condition, but that seems to be more suited > for synchronising between threads, which isn't really the issue here > (and thus it seems like overkill for solving the problem of replacing > that loop with something more efficient, though could be a possibility, > I suppose). But that problem *is* about thread synchronization. Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Tue Nov 21 17:41:03 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 21 Nov 2006 16:41:03 -0600 Subject: Is there a list comprehension for this? In-Reply-To: <1164143944.874745.19470@f16g2000cwb.googlegroups.com> References: <1164143944.874745.19470@f16g2000cwb.googlegroups.com> Message-ID: liam_herron wrote: > Given: > dw = [ 1, -1.1, +1.2 ] > > Suppose I want to create a list 'w' that is defined as > > w[0] = dw[0], > w[1] = w[0] + dw[1], > w[2] = w[1] + dw[2] > > Is there a list comprehension or map expression to do it in one or 2 > lines. One way is to use numpy (numpy.scipy.org): In [40]: from numpy import cumsum In [41]: dw = [1, -1.1, +1.2] In [42]: cumsum(dw) Out[42]: array([ 1. , -0.1, 1.1]) If you're doing a lot of numerical computing, you'll probably want a number of other things that numpy provides. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Thu Nov 16 11:29:46 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 16 Nov 2006 17:29:46 +0100 Subject: Secure Python References: <455c1665@quokka.wn.com.au> <455c4d9b@quokka.wn.com.au> <4s38t9Ftln2aU1@mid.uni-berlin.de> <1163689149.613418.40020@b28g2000cwb.googlegroups.com> Message-ID: <4s3hvqFtih71U1@mid.uni-berlin.de> > A significant issue is the architecture of the server itself. Is a > per-process solution acceptable or must everything happen in the same > process with lots of threads (or microthreads)? Of course, there are > games using lots of microthreads, although I'm not sure whether they > also use lots of processes, too, and it has been asserted that having > lots of operating system threads or processes is just too resource > intensive, but I think it's especially worth considering the nature of > the platform you're using and what it offers. AFAIK most engines today are only single-threaded. A big grief for all those dual-core owners out there. And having thousands of players is common - spawning a process for each of them certainly too resource-consuming. AFAIK stackless python was initially financially supported by a game-company. So I guess that shows us pretty much what games (at least) are after: low-profile in-process threads, fine-grained controllable. Diez From fredrik at pythonware.com Tue Nov 21 01:50:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Nov 2006 07:50:39 +0100 Subject: move up a level In-Reply-To: <1164089267.967125.190860@m73g2000cwd.googlegroups.com> References: <1164089267.967125.190860@m73g2000cwd.googlegroups.com> Message-ID: rplobue at yahoo.com wrote: > alright, noob question: i want to open a file in a directory above the > current one i'm in. I'm trying to use myfile = > open('../thefileiwant.txt', 'r') but the ../ doesn't work. that's how it's usually done. what does "doesn't work" mean in this case? From g.brandl-nospam at gmx.net Thu Nov 16 12:17:48 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 16 Nov 2006 18:17:48 +0100 Subject: atexit.register does not return the registered function. IMHO, it should. In-Reply-To: References: <1163693028.543926.163320@f16g2000cwb.googlegroups.com> Message-ID: Skip Montanaro schrieb: >> Since that the decorator syntax is upon us, I think it would be good if >> atexit.register() was returning the function passed as argument. This >> simple change to the library would solve a problem with the use of >> atexit.register as a decorator (and I can't think of any use case where >> this change would break any code). > ... > > Can you submit a bug report to the SourceForge bug tracker? I'll take > care of the problem when I have access to the subversion repository. Sorry, didn't read this thread before the bug report, which is why I already handled this one ;) cheers, Georg From blah at blahdeblah Thu Nov 30 02:58:48 2006 From: blah at blahdeblah (bill ramsay) Date: Thu, 30 Nov 2006 20:58:48 +1300 Subject: detecting that a SQL db is running Message-ID: <783tm2dmb6brnptr91hsfnc1t38u1utbi8@4ax.com> Hi I wonder if anyone can help me with a problem that I have with MSDE SQL db. [I am changing to SQL server soon]. I have an app that runs on a server that communicates with remote devices using email, this and other similar servers then sends XML/SOAP messages to a master application. I am in the process of intercepting these XML messages and forwarding them on to a service managment platform for notification alerts etc. This app reads a SQL db to get some additional information which is also included in the XML message. the problem is that the app on the comms server is an aggregate of modules, that has a tendency to lock up, the server still runs, but it causes the SQL server to stop. This is being worked on by the developers, i expect that it will take some time to resolve. using ASR we just reboot the server when this happens. Using simple SQL statements, i am able to detect when SQL is up and running, and to detect when it has stopped. Is there a simple way to detect if the SQL server has actually started? i had a look at investigating the registry, but to be honest, from the various recipes that i have seen, i haven't a clue what I am looking at, any advice? any information shall be gratefully received kind regards Bill From hardcoded.software at gmail.com Mon Nov 20 07:15:14 2006 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 20 Nov 2006 04:15:14 -0800 Subject: to ask an container instance to suicide In-Reply-To: <1164015742.696913.283050@m73g2000cwd.googlegroups.com> References: <1164015742.696913.283050@m73g2000cwd.googlegroups.com> Message-ID: <1164024914.819226.14840@m7g2000cwm.googlegroups.com> jm.suresh at no.spam.gmail.com wrote: > Hi, > I have containers to hold geometrical objects. The members in these > containers can again be containers them self. Now, In the program I > would be moving objects from one container to another. In this process, > If the number of members in one of the containers becomes just one, I > want to delete that container and have only its only member in place of > it in the parent container. > I have implemented setting and getting the container members using > property(). > > Right now, I am planning to do this this way: > Maintain a reference to parent container in each container. > When the condition is detected, do self.parent.deleteObject(self) . > > def deleteObject(self,memberId): > index = self._members.index(memberId) > self._members[index] = memberId._members[0] > del memberId > > Will this work. Or is there any other simple way to do this? > -- > Suresh I don't understand what you want to achieve, but there are 2 things I can say: "del memberId" is useless, it is deleted anyway when memberId goes out of scope. Because you have a 2-way reference, have one of them (the parent reference would be better) a weakref. Else, you'll be leaking memory. From ndbecker2 at gmail.com Sun Nov 12 08:24:48 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Sun, 12 Nov 2006 08:24:48 -0500 Subject: Find interface associated with default route? References: Message-ID: Neal Becker wrote: > Fredrik Lundh wrote: > >> Neal Becker wrote: >> >>> Any thoughts on howto find the interface associated with the default >>> route (this is on linux)? >> >> are you sure you sent this to the right newsgroup ? >> >> is this what you want ? >> >> >>> import os >> >>> for line in os.popen("/sbin/route"): >> ... line = line.split() >> ... if line[0] == "default": >> ... print line[-1] >> ... >> eth0 >> > > Well, I was hoping for something more 'elegant' - meaning relying on > library > calls rather than calling programs. Obviously, /sbin/route has some > library calls to obtain this info, and maybe python has a wrapper for it. > > Yes, this is the right group - I want a python solution. > A quick strace reveals that 'route' just reads /proc/net/route, so: def get_default_if(): f = open ('/proc/net/route', 'r') for line in f: words = string.split (line) dest = words[1] try: if (int (dest) == 0): interf = words[0] break except ValueError: pass return interf From g.brandl-nospam at gmx.net Wed Nov 8 15:24:36 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 08 Nov 2006 21:24:36 +0100 Subject: Is there a commas-in-between idiom? In-Reply-To: References: Message-ID: Peter van Kampen schrieb: > On 2006-11-06, Fredrik Lundh wrote: >> I've collected a bunch of list pydioms and other notes here: >> >> http://effbot.org/zone/python-list.htm > > """ > A = B = [] # both names will point to the same list > """ > > I've been bitten by this once or twice in the past, but I have always > wondered what it was useful for? Can anybody enlighten me? Do you never have a situation where you want to assign the same value to two variables? Or are you objecting to the fact that both names point to the same object? It couldn't be otherwise. Consider: X = [] A = B = X What should this do? Copy "X" and assign one copy to A, one to B? Georg From bmichel at gmail.com Wed Nov 22 08:00:32 2006 From: bmichel at gmail.com (bmichel at gmail.com) Date: 22 Nov 2006 05:00:32 -0800 Subject: XML Validation in Python using XSV Message-ID: <1164200431.878328.175100@f16g2000cwb.googlegroups.com> I'd like to use XSV for validating an XML file in Python. I am working on Linux Debian platform. I'm not sure how to install XSV and how to configure it. My goal is to be able to import the XSV library in Python and be able to use it's functions. XSV v2.10 for Debian available here: ftp://ftp.cogsci.ed.ac.uk/pub/XSV/XSV_2.10-1_all.deb How do i do that? From sjmachin at lexicon.net Fri Nov 17 05:53:01 2006 From: sjmachin at lexicon.net (John Machin) Date: 17 Nov 2006 02:53:01 -0800 Subject: Bitwise operators. Differences from javascript and PHP. In-Reply-To: References: <1163756475.924108.202060@h48g2000cwc.googlegroups.com> <1163758737.890309.21950@e3g2000cwe.googlegroups.com> Message-ID: <1163760781.357871.78220@k70g2000cwa.googlegroups.com> On Nov 17, 9:38 pm, Fredrik Lundh wrote: > John Machin wrote: > >http://theopensourcery.com/phplogic.htm > > > "In effect the bitwise operations [words "can be" omitted, I presume]"can only be", more likely. Yes, probably. > > > safely applied to integer variables - their effect on booleans, > > float/double or string variables can be predicted but are not really > > useful" ???sounds like we're in > > >>> v = float(4653896912) > >>> from string import pack, unpack from struct, more likely? > >>> o = unpack("i", pack("d", v)[:4])[0] > >>> (-o>>(13-3))|-2<<(32-13-1) > -212992 > > territory. > Sounds like you could be correct. However it's possible that you have aided and abetted the OP to perpetrate a nonsense :-) Cheers, John From martin.witte at gmail.com Fri Nov 17 02:51:08 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 16 Nov 2006 23:51:08 -0800 Subject: problem with defining a global class instance In-Reply-To: References: Message-ID: <1163749868.058194.71000@b28g2000cwb.googlegroups.com> sharath B N wrote: > hi, > i am sort of newbie to python. I am trying to do a super Market > simulation with OOP in python. I have problems with using a class > instance as global... > def generate (... ,....,...) > > " in this function i define the global variables " > global stock,stockManager, manager etc. > > > class Manager > ... > ... > ... > def create_stockManager(..) > """ this is a method in class manager""" > stockManager = StockManager( name) > stockManager.create_Stock(..) > > > now this gives an attribute error sayin .... stockManager has no > attribute create_Stock > > if i create the StockManager instance in the generate func > itself...then this problem doesnt come....but i need it this way for > the program to make sense.. > can somebody help me > thnks > Sharath Python uses the concept of namespaces, the keyword 'global' binds a local variable to the global namespace, take as example: # this amount is in the global namespace amount = 98 def get_amount_local(): # this amount is local in this function amount = 23 return amount def get_amount_global(): # this global is taken from the gloabl namespace global amount return amount print get_amount_local() # so this will print 23 print get_amount_global() # so this will print 98 see http://docs.python.org/ref/assignment.html From Fredrik.Kant at tradetech.se Thu Nov 23 12:44:37 2006 From: Fredrik.Kant at tradetech.se (Kant, Fredrik) Date: Thu, 23 Nov 2006 17:44:37 -0000 Subject: javadoc equivalent? Message-ID: <89ECB4622A5FC84ABC9BFBD2F0488DC438F91C@stockholm.ttg.local> Hi! I saw this question, have you tried the standard python module pydoc (you find it under Lib in the standard installation)? Fredrik Kant Phone: +46 (8) 4100 9795 Mobile: +46 (733) 38 50 42 Email: fredrik.kant at tradetech.se TradeTech Sturegatan 46 SE-114 36 Stockholm, SWEDEN www.tradetech.se Confidentiality Notice The content of this e-mail message is intended only for the confidential use of the person(s) to whom it is addressed above. If the reader of this message is not the designated person to whom it is addressed, you are hereby notified that you have received this communication in error and that reading it, copying it, or in any way disseminating its content to any other person, is strictly prohibited. If you have received this e-mail in error, please notify the author by using the reply key immediately. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Fri Nov 24 09:39:54 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 24 Nov 2006 06:39:54 -0800 Subject: How do I access a main frunction from an import module? In-Reply-To: <1164377547.562483.152770@l12g2000cwl.googlegroups.com> References: <1164377547.562483.152770@l12g2000cwl.googlegroups.com> Message-ID: <1164379194.770281.315460@j72g2000cwa.googlegroups.com> Jim wrote: > I have created an import module. And would like to access a function > from the main script, e.g., > > file abc.py: > ################### > def a(): > m() > return None > #################### > > file main.py: > ##################### > from abc import * > def m(): > print 'something' > return None > > a() > ###################### You can do it with "from __main__ import m" atop abc.py (the module invoked at the command line is always called __main__). However, I *highly* suggest you put m in another file. Importing variables from __main__ would make your program incompatible with many useful tools. For example, if you invoke the Python profiler on your code, like this: python -m profile main.py it will break your code, because __main__ no longer refers to main.py but to profile.py (from the Python library). Importing from __main__ adversely affects tools such as PyChecker and PyLint. The exception to this would be if abc.py is specifically designed as a utility for interactive use; then it would be ok and useful. Carl Banks From tleeuwenburg at gmail.com Thu Nov 30 23:14:43 2006 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 30 Nov 2006 20:14:43 -0800 Subject: Open and closing files In-Reply-To: <1164942954.646364.143010@h54g2000cwb.googlegroups.com> References: <1164942954.646364.143010@h54g2000cwb.googlegroups.com> Message-ID: <1164946483.219843.47740@f1g2000cwa.googlegroups.com> John Machin wrote: > Thomas Ploch wrote: > > Is it defined behaviour that all files get implicitly closed when not > > assigning them? > > > > Like: > > > > def writeFile(fName, foo): > > open(fName, 'w').write(process(foo)) > > > > compared to: > > > > > > def writeFile(fName, foo): > > fileobj = open(fName, 'w') > > fileobj.write(process(foo)) > > fileobj.close() > > > > Which one is the 'official' recommended way? > > No such thing as an 'official' way. > > Nothing happens until the file object is garbage-collected. GC is > generally not under your control. > > Common sense suggests that > (a) when you are reading multiple files, you close each one explicitly > (b) when you are writing a file, you close it explicitly as soon as you > are done with it. That way you can trap any error condition and do > something moderately sensible -- better than getting an error condition > during GC when your Python process is shutting down. > > HTH, > John Not to mention you can get bitten on the ass by a few characters sitting in a buffer someplace when you expect your file to have been fully written. Close the thing. Cheers, -T From dannycolligan at gmail.com Tue Nov 21 12:48:56 2006 From: dannycolligan at gmail.com (Danny Colligan) Date: 21 Nov 2006 09:48:56 -0800 Subject: Vim scripts for editing Python? In-Reply-To: <1164127733.241526.126200@m7g2000cwm.googlegroups.com> References: <1164086261.774376.125490@j44g2000cwa.googlegroups.com> <1164127733.241526.126200@m7g2000cwm.googlegroups.com> Message-ID: <1164131336.302547.222060@k70g2000cwa.googlegroups.com> On Nov 21, 11:48 am, "Danny Colligan" wrote: > Rainy wrote: > > Hi, did anyone make a good set of scripts for editing Python in Vim? I > > know there is one on vim.org but it isn't very advanced. thx..Here's what google has to say about it:http://www.google.com/search?hl=en&q=site%3Ahttp%3A%2F%2Fwww.vim.org%...http://www.google.com/search?hl=en&lr=&safe=off&q=site%3Ahttp%3A%2F%2... > > Danny Almost forgot... if you do some searching around on comp.editors for vim and python: http://groups-beta.google.com/group/comp.editors/search?group=comp.editors&q=vim+python&qt_g=Search+this+group You'll find some helpful threads such as this one: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7678e4269a806476/c65a6a9ed84e0eb2?lnk=gst&q=python&rnum=5#c65a6a9ed84e0eb2 Danny From pavlovevidence at gmail.com Mon Nov 13 19:22:03 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 13 Nov 2006 16:22:03 -0800 Subject: Python 3000 idea -- + on iterables -> itertools.chain In-Reply-To: <1163430016.542861.130100@b28g2000cwb.googlegroups.com> References: <1163385266.824914.265490@b28g2000cwb.googlegroups.com> <1163408380.747399.18750@h54g2000cwb.googlegroups.com> <1163417909.768399.199650@h54g2000cwb.googlegroups.com> <1163430016.542861.130100@b28g2000cwb.googlegroups.com> Message-ID: <1163463723.056150.184690@m7g2000cwm.googlegroups.com> George Sakkis wrote: > Carl Banks wrote: > > George Sakkis wrote: > > > If by 'respond to "+"' is implied that you can get a "TypeError: > > > iterable argument required", as you get now for attempting "x in y" for > > > non-iterable y, why not ? > > > > Bad idea on many, many levels. Don't go there. > > Do you also find the way "in" works today a bad idea ? Augh. I don't like it much, but (assuming that there are good use cases for testing containment in iterables that don't define __contains__) it seems to be the best way to accomplish it for iterables in general. However, "in" isn't even comparable to "add" here. First of all, unlike "add", the nature of "in" more of less requires that the second operand is some kind of collection, so surprises are kept to a minimum. Second, testing containment is just a bit more important, and thus deserving of a special case, than chaining iterables. The problem is taking a very general, already highly overloaded operator +, and adding a special case to the interpreter for one of the least common uses. It's just a bad idea. > > 3. While not breaking backwards compatibility in the strictest sense, > > the adverse effect on incorrect code shouldn't be brushed aside. It > > would be a bad thing if this incorrect code: > > > > a = ["hello"] > > b = "world" > > a+b > > > > suddenly started failing silently instead of raising an exception. > > That's a good example for why I prefer an iterator rather than an > iterable algebra; the latter is too implicit as "a + b" doesn't call > only __add__, but __iter__ as well. On the other hand, with a concrete > iterator type "iter(a) + iter(b)" is not any more error-prone than > 'int(3) + int("2")' or 'str(3) + str("2")'. > > What's the objection to an *iterator* base type and the algebra it > introduces explicitly ? Well, it still makes it more work to implement iterator protocol, which is enough reason to make me -1 on it. Anyways, I don't think it's very useful to have it for iterators because most people write functions for iterables. You'd have to write "iter(a)+iter(b)" to chain two iterables, which pretty much undoes the main convenience of the + operator (i.e., brevity). But it isn't dangerous. Carl Banks From mail at microcorp.co.za Mon Nov 20 01:12:15 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 20 Nov 2006 08:12:15 +0200 Subject: Getting value from Tkinter entry widget: variable scope difficulty References: Message-ID: <01c101c70c6b$c06f44a0$03000080@hendrik> "Kevin Walzer" > I'm trying to construct a simple Tkinter GUI and I'm having trouble with > getting the value of an entry widget and passing it onto a callback > function. But I'm not grokking variable scope correctly. > > I have two functions. Here are the relevant excerpts: > > def makeGUI(): > > ###lots of code to set up toplevel windows > > searchbutton=Button(topframe, image=searchglass, command=doSomething) > searchbutton.image=searchglass > searchbutton.pack(side=LEFT, expand = NO) > > searchterm=StringVar() this will make a new local variable - if you want to assign to the global one, you need to add a global statement before doing this, in this makeGUI function. - you can read the global here if you have defined searchterm in an outer scope, but the assign will make a new local one. > > entryterm=Entry(topframe, textvariable=searchterm) > entryterm.pack(side=RIGHT) > > entrylabel=Label(topframe, text="Search:") > entrylabel.pack(side=RIGHT) > > > def doSomething(): > > file = os.popen('systemcommand %s' % searchterm, 'r') here searchterm seems to be a command line variable. look in the help for sys.argv how to access command line variables - not that you need to, but its good to know... :-) had makeGUI been a class instead of a function, you could have written makeGUI.searchterm here, without mucking around with globals.... > > print searchterm > > --- > > What I want to happen is the value of searchterm to be passed on to the > doSomething() call when the searchbutton is pressed. Right now it > appears the value of "searchterm" is local to each function. > True > In Tcl this would be handled by simply assigning the variable > "searchterm" to the global namespace in each function, i.e. "global > searchterm." I've looked and can't quite figure out how to do this in > Python. Any advice is appreciated. global searchterm # - in outer scope global searchterm # - in inner scope before assign HTH - Hendrik From rpdooling at gmail.com Fri Nov 24 11:47:16 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 24 Nov 2006 08:47:16 -0800 Subject: Active State and Komodo... References: Message-ID: <1164386836.507478.100330@f16g2000cwb.googlegroups.com> Steve Thompson wrote: > On Fri, 24 Nov 2006 06:35:21 -0500, Steve Thompson wrote: > > > Addionally, is the eric IDE (version 3) an acceptible IDE or are there > > more easy and more productive IDE's for perl? Perl? You're on a Python list? Anyway, the subject of IDEs comes up every other day. If you want comparisons or discussion of Eric and Python, search the group for "Eric IDE" http://groups.google.com/group/comp.lang.python/search?q=eric+ide&start=0&scoring=d& If the link breaks, use: http://tinyurl.com/yxy8vv I use vim 7.0 and Komodo myself. Both are cross platform. You'll see hundreds of different opinions here. rd "A couple of months in the laboratory can save a couple of hours in the library." From guettli.usenet at thomas-guettler.de Tue Nov 28 10:21:49 2006 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 28 Nov 2006 15:21:49 GMT Subject: HTML Table-of-Content Extraction Script References: Message-ID: <4t32gdF118i0hU1@mid.individual.net> robert wrote: > I'm looking for a function which extracts a table of contents of HTML file(s) from ... and possibly auto-creates the ancors. > Maybe something already exists? You can try mine: http://www.thomas-guettler.de/scripts/number-html-headings.py.txt -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From meyer at acm.org Fri Nov 24 12:05:30 2006 From: meyer at acm.org (Andre Meyer) Date: Fri, 24 Nov 2006 18:05:30 +0100 Subject: synching with os.walk() In-Reply-To: <1164386233.446742.67640@f16g2000cwb.googlegroups.com> References: <1164385629.462106.106120@j72g2000cwa.googlegroups.com> <1164386233.446742.67640@f16g2000cwb.googlegroups.com> Message-ID: <7008329d0611240905n597c4140kb063d15ab424f8ad@mail.gmail.com> What I forgot to mention is that I want this to run unmodified from both Windows and Linux (and Mac). Otherwise, there are enough options to choose from, besides developing it myself, I guess. On 24 Nov 2006 08:37:13 -0800, Paddy wrote: > > > Paddy wrote: > > > Andre Meyer wrote: > > > > > Hi all > > > > > > os.walk() is a nice generator for performing actions on all files in a > > > directory and subdirectories. However, how can one use os.walk() for > walking > > > through two hierarchies at once? I want to synchronise two directories > (just > > > backup for now), but cannot see how I can traverse a second one. I do > this > > > now with os.listdir() recursively, which works fine, but I am afraid > that > > > recursion can become inefficient for large hierarchies. > > > > > > thanks for your help > > > Andr? > > > > Walk each tree individually gathering file names relative to the head > > of the tree and modification data. > > > > compare the two sets of data to generate: > > 1. A list of what needs to be copied from the original to the copy. > > 2. A list of what needs to be copied from the copy to the original > > > > Do the copying. > > > > |You might want to show the user what needs to be done and give them > > the option of aborting after generating the copy lists. > > > > - Paddy. > P.S. If you are on a Unix type system you can use tar to do the copying > as you can easily compress the data if it needs to go over a sow link, > and tar will take care of creating any needed directories in the > destination if you create new directories as well as new files. > - Paddy. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Dr. Andre P. Meyer http://python.openspace.nl/meyer TNO Defence, Security and Safety http://www.tno.nl/ Delft Cooperation on Intelligent Systems http://www.decis.nl/ Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. - Douglas Adams -------------- next part -------------- An HTML attachment was scrubbed... URL: From bla at bla.com Thu Nov 30 10:45:34 2006 From: bla at bla.com (Vincent Delporte) Date: Thu, 30 Nov 2006 16:45:34 +0100 Subject: "fork and exit" needed? References: <8osmm21skionildtnme1j0nvqbla6oqk72@4ax.com> <7nqtm25fq8vk4jlu577n974hgei3ese3g7@4ax.com> Message-ID: On Thu, 30 Nov 2006 10:18:24 -0500, "Mike C. Fletcher" wrote: >which is how Linux knows what interpreter to use for the script. Thanks. That's what I found out after a bit more research. I didn't pay attention to this because it's not needed to run under Windows, and I was focusing on the fork() and stdout thing. From anderslanglands at gmail.com Wed Nov 22 09:43:55 2006 From: anderslanglands at gmail.com (anders) Date: 22 Nov 2006 06:43:55 -0800 Subject: PyQt app in seperate thread In-Reply-To: References: <1164199026.728638.180000@j44g2000cwa.googlegroups.com> <1164204404.675906.59020@b28g2000cwb.googlegroups.com> Message-ID: <1164206635.601219.36860@j44g2000cwa.googlegroups.com> Phil Thompson wrote: > On Wednesday 22 November 2006 2:06 pm, anders wrote: > > Phil Thompson wrote: > > > On Wednesday 22 November 2006 12:37 pm, anders wrote: > > > > I am writing a plugin for a piece of software in python, and I want to > > > > start up a PyQt GUI in the plugin, without stalling the main thread > > > > while the gui is running (later i will want to pass messages between > > > > the main thread and the gui thread). > > > > > > > > I'm new to pyqt, so I'm probably doing something very silly, but for > > > > the moment I'm just trying to get the first pyqt tutorial example > > > > running in a seperate thread: > > > > > > > > ----8<-------- > > > > > > > > import sys > > > > from PyQt4 import QtGui > > > > from PyQt4 import QtCore > > > > > > > > class MyThread( QtCore.QThread ): > > > > def __init__( self ): > > > > QtCore.QThread.__init__( self ) > > > > > > > > def run( self ): > > > > app = QtGui.QApplication( sys.argv ) > > > > hello = QtGui.QPushButton( 'Hello world!' ) > > > > hello.resize( 500, 500 ) > > > > hello.show() > > > > app.exec_() > > > > QtCore.QThread.terminate( ) > > > > > > > > > > > > > > > > mt = MyThread() > > > > mt.start() > > > > print 'Main thread continuing...' > > > > mt.wait() > > > > print 'GUI thread finished.' > > > > > > > > ----8<-------- > > > > > > > > The app starts up (with a warning WARNING: QApplication was not created > > > > in the main() thread. ). I get a window, but no button, and clicking on > > > > the close button does nothing and I have to force the program to quit. > > > > > > > > There's got to be a way to get this working, right? Can anyone help me > > > > along the right path? > > > > > > Read http://doc.trolltech.com/4.2/threads.html > > > > > > In particular the bit that says that exec_() must be called from the main > > > thread and not from a QThread. > > > > > > Phil > > > > OK so that's all good... so how do I go about doing what I want then? > > Can I set up a window in the second thread and start its event loop > > without running the event loop in the core app? > > No. Read the second sentence of the paragraph I referred to. Also read the > section "QObject Reentrancy". > > Phil OK I see that now. Thanks for pointing that out. So basically, I can't do what I want at all. That's a bit of a pain. Is there no way of tricking Qt into thinking I'm running it in the main thread? A From cbarbez at gmail.com Sun Nov 12 08:07:03 2006 From: cbarbez at gmail.com (DarkPearl) Date: 12 Nov 2006 05:07:03 -0800 Subject: service windows avec py2exe References: <1163157344.987173.259940@i42g2000cwa.googlegroups.com> <1163242265.307783.122230@f16g2000cwb.googlegroups.com> Message-ID: <1163336823.477761.68070@m7g2000cwm.googlegroups.com> ok, It's this line who crash the service : self.WMIService =win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") why this function goes when it is not a service? with IDLE -> ok with py2exe executable (no windows service) -> ok with py2exe service option true (windows service) -> CRASH.... From geskerrett at hotmail.com Tue Nov 28 13:12:36 2006 From: geskerrett at hotmail.com (geskerrett at hotmail.com) Date: 28 Nov 2006 10:12:36 -0800 Subject: Reading text labels from a Win32 window Message-ID: <1164737556.265751.38680@l12g2000cwl.googlegroups.com> Does anyone know of a way to read text labels from a Win32 application. I am familiar with using pywin32 and the SendMessage function to capture text from Buttons,text boxex, comboboxes, etc, however, the text I am would like to capture doesn't appear to be in a control. From jweida at gmail.com Mon Nov 6 14:11:19 2006 From: jweida at gmail.com (Jerry) Date: 6 Nov 2006 11:11:19 -0800 Subject: adding python scripting to my application In-Reply-To: <1162794251.047389.297800@e3g2000cwe.googlegroups.com> References: <1162794251.047389.297800@e3g2000cwe.googlegroups.com> Message-ID: <1162840279.875373.301550@f16g2000cwb.googlegroups.com> I am not a Python guru by any means, but I believe that when an application says that you can "script" their application with Python, it means that you can actually write Python code to interact with the application. Embedding may be the same thing. Extending (as I read it) involves writing portions of your program in Python and have do the logic portions. If you would like to allow users to write small scripts that interact with your program and control it (a la VBScript or AppleScript), then I believe embedding Python in your program is what you want. If you would like Python to run various parts of your program in order to make some portions easier to write/manage/whatever, then you want to "extend" your program using Python. The key difference being that you aren't providing a way for someone else to interact with your program using Python if you are extending. Again, I am not a guru and a read through the docs on python.org would probably be the best place to get sound technical advice on these subjects. -- Jerry From fredrik at pythonware.com Wed Nov 15 04:13:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Nov 2006 10:13:48 +0100 Subject: Difference In-Reply-To: <1163579012.18671.10.camel@localhost> References: <1163579012.18671.10.camel@localhost> Message-ID: Hodren Naidoo wrote: > Can someone plz tell me the differences between redirect and traverse in > python metadata? it's not clear what you mean by "redirect", "traverse" or "python metadata", so that's not very likely. From spedrosa at gmail.com Thu Nov 16 16:07:39 2006 From: spedrosa at gmail.com (Stephen Eilert) Date: 16 Nov 2006 13:07:39 -0800 Subject: Will GPL Java eat into Python marketshare? In-Reply-To: <455cc9ae$1@news.unimelb.edu.au> References: <1163624095.187124.88670@e3g2000cwe.googlegroups.com> <455b978c$1@news.unimelb.edu.au> <_jT6h.7906$ig4.2956@newsread2.news.pas.earthlink.net> <455cc9ae$1@news.unimelb.edu.au> Message-ID: <1163711259.597170.116020@e3g2000cwe.googlegroups.com> Maurice LING escreveu: > > > > I once wrote a partial JVM in Modula-3 (strictly a researchware > > effort), so I can imagine it being done technically. But why? > > > > The big problem with Java-and-Python is not the VMs underneath. It is > > the fact that Java has layers upon layers upon layers of idiosyncratic > > libraries and idioms. When you write bindings to that world (even if > > the bindings are generated automagically), you have to *think* in > > those same layers. The Python-oriented developer suddenly has to use > > a dozen imports in order to do things already done better in > > Pythonesque libraries. > > > > The main use I can see is to be able to incorporate Java applications > into Python. For example, I am using Cytoscape (www.cytoscape.org) which > is in Java. I do hope that I can control Cytoscape from Python and > manipulate its objects from Python. > > Say given cytoscape.jar, I'll like to be able to do this: > > >>> from cytoscape javaimport cytoscape > >>> c = cytoscape() > > And the tighest way I see that this can be done is for Python VM to > execute Java bytecodes like Python bytecodes. That is, Python VM > executes Java bytecodes directly and not through object mapping which I > think is that JPyPe is doing. > > I must say that this is part of even a fluffier dream that one day, I > can take any applications and play around with it in Python. Currently, > my collaborators wrote in Perl and Java, so it is not easy for me to use > their work in my work. > > ML What is wrong with the other way around and Jython? Just curious. Stephen From bearophileHUGS at lycos.com Sun Nov 26 05:47:30 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Nov 2006 02:47:30 -0800 Subject: problem about list indexing In-Reply-To: <1164537532.420669.323520@45g2000cws.googlegroups.com> References: <1164529513.862598.221550@h54g2000cwb.googlegroups.com> <1164533754.269071.149590@n67g2000cwd.googlegroups.com> <1164537532.420669.323520@45g2000cws.googlegroups.com> Message-ID: <1164538050.587119.190790@n67g2000cwd.googlegroups.com> hollowspook: > how about indexing 1-7, 10 > [range(1:8),10] will generate [[1, 2, 3, 4, 5, 6, 7], 10], instead of > [1, 2, 3, 4, 5, 6, 7, 10] (Note that range(1:8) is a syntax error). You can join and extend lists as you like: >>> range(1, 8) + [10] [1, 2, 3, 4, 5, 6, 7, 10] See also the list.append and list.extend methods too. Bye, bearophile From deets at nospam.web.de Sun Nov 19 09:32:13 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 19 Nov 2006 15:32:13 +0100 Subject: lxml/ElementTree and .tail In-Reply-To: <1163945474.011407.218600@m7g2000cwm.googlegroups.com> References: <455C1887.6060602@web.de> <1163671192.876928.35960@f16g2000cwb.googlegroups.com> <761846B7-E374-41FE-8804-CBB3D42FD4D2@snowtide.com> <0wD7h.77$_H5.56@tornado.texas.rr.com> <1163945474.011407.218600@m7g2000cwm.googlegroups.com> Message-ID: <4sb87dFv0rtkU1@mid.uni-berlin.de> > You'll be surprised at how many XMLers agree that Web services are a > pretty inept reinvention of CORBA. I was pretty much slain by this > take: > > http://wanderingbarque.com/nonintersecting/2006/11/15/the-s-stands-for-simple Thanks for that! Sums up nicely my experiences, and gave me a good chuckle! While I liked the idea of AXIS reflecting my java code in the first place (as long as interoperability only meant "I can test my own code"), it sucked soooo hard when trying to make it work with anything else (including python of course). And I don't know why I've complained about this style of inverse interface generation on so many other occasions (e.g. COM interfaces in VStudio, JBuilder GUI design and so on), but could never quite put the finger on what disturbed me on SOAP. Probably because looking at a WSDL it immediately made me shrink away from that mess and hope that there must be _some_ merciful deity that will produce that crap for me, so that I never asked myself the right questions.... Diez From paddy3118 at netscape.net Wed Nov 15 02:10:07 2006 From: paddy3118 at netscape.net (Paddy) Date: 14 Nov 2006 23:10:07 -0800 Subject: refactoring so that multiple changes can be made with one variable? In-Reply-To: <455a3a7f$0$32421$c3e8da3@news.astraweb.com> References: <4559e396$0$32430$c3e8da3@news.astraweb.com> <1163522075.704650.40850@i42g2000cwa.googlegroups.com> <455a3a7f$0$32421$c3e8da3@news.astraweb.com> Message-ID: <1163574607.417931.139260@e3g2000cwe.googlegroups.com> John Salerno wrote: > Paddy wrote: > > > You could keep a handle on all object instances created then go through > > the objects making appropriate changes, e.g: > > > > > > class Character(object): > > instances = [] > > def __init__(self, name, strength, dexterity, intelligence): > > instances.append(self) > > # as before ... > > def mod_instances(self): > > for inst in instances: > > inst.some_property += 1 # or whatever > > # (Untested) > > But doesn't this require that the change be predetermined so you can > code it into the method? > > I don't necessarily need a programmatic way to do this, just a simple > way to go back to the code and edit a single thing, instead of having to > update all the numbers. I just put in a simple version of mod_instances. mod_instances could take a function as an argument the napply the function to all instances, e.g: def mod_func1(inst): inst.abc += inst.xyz # or whatever class Character(object): instances = [] def __init__(self, name, strength, dexterity, intelligence): instances.append(self) # as before ... def mod_instances(self, mod_func): for inst in instances: mod_func(inst) You can define different mod_func, like mod_func1 to make whatever changes to the instances. From johnzenger at gmail.com Wed Nov 29 22:53:24 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 29 Nov 2006 19:53:24 -0800 Subject: a quickie: range - x In-Reply-To: <1164858136.495250.180790@14g2000cws.googlegroups.com> References: <1164858136.495250.180790@14g2000cws.googlegroups.com> Message-ID: <1164858804.368067.274270@16g2000cwy.googlegroups.com> (x for x in xrange(N+1) if x != m) rjtucke wrote: > I want an iterable from 0 to N except for element m (<=M). > I could write > x = range(N) > x.remove(m) > but I want it in one expression. > > Thanks, > Ross From john106henry at hotmail.com Fri Nov 17 14:00:39 2006 From: john106henry at hotmail.com (John Henry) Date: 17 Nov 2006 11:00:39 -0800 Subject: How fuzzy is get_close_matches() in difflib? In-Reply-To: References: <1163724049.225348.118020@h54g2000cwb.googlegroups.com> <1163737190.118975.227740@h48g2000cwc.googlegroups.com> <1163746781.666937.63970@h48g2000cwc.googlegroups.com> Message-ID: <1163790039.738976.294330@m7g2000cwm.googlegroups.com> Steven D'Aprano wrote: > > >>> s = difflib.SequenceMatcher(None, "HIDEDCT1", "HIDESCT1") > >>> t = difflib.SequenceMatcher(None, "HIDEDST1", "HIDESCT1") > >>> > >>> for block in s.get_matching_blocks(): > ... print "a[%d] and b[%d] match for %d elements" % block > ... > a[0] and b[0] match for 4 elements > a[5] and b[5] match for 3 elements > a[8] and b[8] match for 0 elements > >>> > >>> for block in t.get_matching_blocks(): > ... print "a[%d] and b[%d] match for %d elements" % block > ... > a[0] and b[0] match for 4 elements > a[5] and b[4] match for 1 elements > a[6] and b[6] match for 2 elements > a[8] and b[8] match for 0 elements > >>> > > I think what you are seeing is an artifact of the precise details of the > pattern matcher. Feel free to subclass the SequenceMatcher or Differ > classes to get the results you expect :-) > Looks like for this particular case, looking at number of matched groups worked better. From john106henry at hotmail.com Fri Nov 17 16:22:19 2006 From: john106henry at hotmail.com (John Henry) Date: 17 Nov 2006 13:22:19 -0800 Subject: remove a list from a list In-Reply-To: <1163792916.095832.259010@m73g2000cwd.googlegroups.com> References: <455E0A20.9000509@tim.thechases.com> <1163792832.404528.187950@k70g2000cwa.googlegroups.com> <1163792916.095832.259010@m73g2000cwd.googlegroups.com> Message-ID: <1163798539.346514.221000@h54g2000cwb.googlegroups.com> OK, if you don't care the resulting order, do it like: class Convert2Dict: def __init__(self, data): self._data={} for x in data: self._data[x.upper()]=x def get(self, key): return self._data[key.upper()] a = ["a", "B"] b = ["c", "a", "A", "D", "b"] b_dict = Convert2Dict(b) b = [b_dict.get(x) for x in list( set([x.upper() for x in b]) - set([x.upper() for x in a]) ) ] John Henry wrote: > Scratch that. b becomes all upper... > > John Henry wrote: > > from sets import Set as set # Python 2.3 > > > > b = list( set([i.upper() for i in b) - set([i.upper() for i in a] ) ) > > > > > > Rares Vernica wrote: > > > Yeah, I ended up doing a similar kind of loop. That is pretty messy. > > > > > > Is there any other way? > > > > > > Thanks, > > > Ray > > > > > > Tim Chase wrote: > > > >> That is a nice solution. > > > >> > > > >> But, how about modifying the list in place? > > > >> > > > >> That is, l would become ['c', 'D']. > > > >> > > > >>> >>> e = ['a', 'b', 'e'] > > > >>> >>> l = ['A', 'a', 'c', 'D', 'E'] > > > >>> >>> s = set(e) > > > >>> >>> [x for x in l if x.lower() not in s] > > > >>> ['c', 'D'] > > > > > > > > > > > > Well...changing the requirements midstream, eh? ;-) > > > > > > > > You can just change that last item to be a reassignment if "l" is > > > > all you care about: > > > > > > > > >>> l = [x for x in l ...] > > > > > > > > Things get a bit hairier if you *must* do it in-place. You'd > > > > have to do something like this (untested) > > > > > > > > for i in xrange(len(l), 0, -1): > > > > if l[i-1].lower() in s: > > > > del l[i-1] > > > > > > > > > > > > which should do the job. > > > > > > > > -tkc > > > > > > > > > > > > From __peter__ at web.de Tue Nov 14 11:17:04 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Nov 2006 17:17:04 +0100 Subject: modules and generated code References: Message-ID: Nigel Rantor wrote: > Peter Otten wrote: >> Nigel Rantor wrote: >>> So, if I have a tool that generates python code for me (in my case, >>> CORBA stubs/skels) in a particular package is there a way of placing my >>> own code under the same package hierarchy without all the code living in >>> the same directory structure. >> http://docs.python.org/lib/module-pkgutil.html > Yep, looks like that should work, but it doesn't. :-/ > > Do you have any idea whether other __init__.py scripts from the same > logical module will still be run in this case? I don't think it will. > The generated code uses its init script to pull in other code. You could invoke it explicitly via execfile("/path/to/generated/package/__init__.py") in the static package/__init__.py. Peter From fredrik at pythonware.com Fri Nov 17 03:33:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 17 Nov 2006 09:33:37 +0100 Subject: determining the bounds of a tuple returned from a database In-Reply-To: <1163746899.262327.72100@h48g2000cwc.googlegroups.com> References: <1163743636.125450.98410@b28g2000cwb.googlegroups.com> <1163744646.708954.271010@f16g2000cwb.googlegroups.com> <1163746899.262327.72100@h48g2000cwc.googlegroups.com> Message-ID: ronrsr wrote: > very sorry, that was my error - len(result[0]) and len(result[1]) both > return 1 -- > > i think I'm misunderstanding what len() does - to me they appear to > have 2 or 3 elements, or at least be composed of a string of some > length. from python's perspective, the data structure you're looking at looks like tuple of tuple of one string tuple of one string tuple of one string etc so len(result) is the number of tuples, and len(result[index]) is the number of strings in the inner tuples (=1). to get at an individual string, do s = result[index][0] to look inside the string, you need to apply the appropriate string operations to extract the data, or split it up in some suitable way. there's no way Python can figure out how a string appears to you; from Python's perspective, it's just a bunch of characters. From __peter__ at web.de Tue Nov 14 04:21:32 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Nov 2006 10:21:32 +0100 Subject: deleteing item from a copy of a list References: <455984b5@quokka.wn.com.au> Message-ID: timmy <"timothy at open-networks.net"> wrote: > i make a copy of a list, and delete an item from it and it deletes it > from the orginal as well, what the hell is going on?!?!?! > > #create the staff copy of the roster > ????????Roster2 = [] > ????????for ShiftLine in Roster: > ????????????????#delete phone number from staff copy > ????????????????Roster2.append(ShiftLine) > ????????????????del Roster2[len(Roster2)-1][1] > > Roster2 should have nothing to do with Roster, right??? doing a print of > both lists confirms that the phone number has been removed from both You seem to have a list of lists and are making a new outer list. The lists inside that outer list are not copied. You can copy them by calling list(item) or copy.copy(item): >>> roster = [ ... ["Tim", "12345", "some more"], ... ["Jack", "54321", "whatever"], ... ] >>> roster2 = [] >>> for item in roster: ... item = list(item) ... del item[1] ... roster2.append(item) ... >>> roster [['Tim', '12345', 'some more'], ['Jack', '54321', 'whatever']] >>> roster2 [['Tim', 'some more'], ['Jack', 'whatever']] Peter From grahamd at dscpl.com.au Thu Nov 23 16:49:08 2006 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 23 Nov 2006 13:49:08 -0800 Subject: WSGI with mod_python (was: Python, WSGI, legacy web application) References: <1164241791.372210.103330@b28g2000cwb.googlegroups.com> <1164285174.400852.237700@j44g2000cwa.googlegroups.com> <1164286028.588780.281510@j44g2000cwa.googlegroups.com> Message-ID: <1164318548.185492.25940@f16g2000cwb.googlegroups.com> Paul Boddie wrote: > Rob De Almeida wrote: > > Ben Finney wrote: > > > I was under the impression that WSGI in mod_python was a rather kludgy > > > way to do WSGI, but I don't know what the alternatives are. CGI? > > > Python http server (e.g. CherryPy)? Something else? > > > > You can use FastCGI or SCGI too, with Apache, lighttpd or Cherokee. > > I think the motivation behind suggesting an Apache solution was that > you'd be able to migrate the PHP resources you already have running in > Apache (I assume, since PHP can run in other places these days) to > mod_python whilst staying within the Apache environment, rather than > having to maintain a number of different environments at the same time. > In other words, you'd write your replacement resources using WSGI (or > whatever) on mod_python (for performance), CGI (for relative > simplicity), or some other connection technology, and then it'd just be > a matter of changing the various directives and having Apache figure it > out. Correct. As example, imagine you have written a mod_python handler which itself interprets how to map a URL to something to implement the URL. This might map to a WSGI application or to some system of basic mod_python handlers. Within the .htaccess file of the directory where all your PHP files live you could then write: PythonHandler myphppagereplacementhandler | .php At this point nothing will happen, but then one could do the following: SetHandler mod_python For the one page called 'index.php' the mod_python handler would be called instead of PHP. As a Python equivalent for each PHP page is written, just need to trigger the mod_python handler to be used by using the Files directive. One could also have different handlers for each page and use Apache to make the selection if wanted to: SetHandler mod_python PythonHandler myphppagereplacementshandler::index Now I am sure that some will say it looks messy, but as far as trying to do a progressive replacement of pages and maintain URLs, it is probably the quickest way. It should be said that any progressive migration like this is likely to be a bit messy. Don't like this, then another way using Apache might be to use mod_rewrite to remap URLs to new URLs which use Python code. Using mod_rewrite can be a pain though. Yet another way may be to use mod_proxy to selectively forward URLs through to a separate back end web server if you are Apache phobic and want to use a web server written in pure Python. Overall, Apache/mod_python has a lot to offer, but from what I have seen most Python web frameworks simply uses it as a jumping off point and not much else. Graham From justsayyes at charter.net Sun Nov 19 05:28:11 2006 From: justsayyes at charter.net (JFletcher) Date: Sun, 19 Nov 2006 02:28:11 -0800 Subject: need help? Message-ID: <001b01c70bc5$6a6d4f80$6400a8c0@genesis> Get Python help at TheScripts [dot] com From allenjo5 at mail.northgrum.com Thu Nov 16 15:45:18 2006 From: allenjo5 at mail.northgrum.com (allenjo5 at mail.northgrum.com) Date: 16 Nov 2006 12:45:18 -0800 Subject: Question about unreasonable slowness Message-ID: <1163709918.739398.194880@b28g2000cwb.googlegroups.com> [ Warning: I'm new to Python. Don't know it at all really yet, but had to examine some 3rd party code because of performance problems with it. ] Here's a code snippet: i = 0 while (i < 20): i = i + 1 (shellIn, shellOut) = os.popen4("/bin/sh -c ':'") # for testing, the spawned shell does nothing print 'next' # for line in shellOut: # print line On my system (AIX 5.1 if it matters, with Python 2.4.3), this simple loop spawning 20 subshells takes .75 sec. Ok, that's reasonable. Now, if I uncomment the two commented lines, which loop over the empty shellOut array, the progam now takes 11 secs. That slowdown seems very hard to believe. Why should it slow down so much? John. From fredrik at pythonware.com Wed Nov 22 04:13:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Nov 2006 10:13:50 +0100 Subject: How to sort list In-Reply-To: References: <1164136547.137154.126740@m73g2000cwd.googlegroups.com> Message-ID: Klaus Alexander Seistrup wrote: > Decorate-sort-undecorate? > > #v+ > > array = [] > > for addr in Emails: > (user, domain) = addr.split('@') > array.append((domain, user, addr)) > # end for > > array.sort() > > SortedEmails = [addr for (user, domain, addr) in array] > > #v- note that DSU is built into Python these days: L.sort(key=transform) so you could use e.g. Emails.sort(key=lambda s: s.partition("@")[::-1]) also see: http://preview.tinyurl.com/yc3qak http://effbot.org/zone/python-list.htm#sorting From msherman77 at yahoo.com Tue Nov 21 14:01:27 2006 From: msherman77 at yahoo.com (Michael S) Date: Tue, 21 Nov 2006 14:01:27 -0500 (EST) Subject: How good is CORBA? In-Reply-To: <6559fb300611211036l306e99d6ibd354dcd285b243@mail.gmail.com> Message-ID: <20061121190127.83586.qmail@web88305.mail.re4.yahoo.com> I learned CORBA many years ago. If I am not mistaken it had two main principles/purposes. One being language neutrality and the other one to make client/server type of programming easier (replacing Remote Procedure Call??). If you are using Python only, language neutrality doesn't really help. You said you're writing web-based applications, and you didn't specify whether you had client/server interaction, so I don't know whether you need it or not. For code reuse (if that's the issue) you could use subclassing and/or putting stuff into modules. Hope I made some sense. Michael --- Sai Krishna M wrote: > Hi everybody, > > i have been developing web based applications using > python+cheetah. > > The numbers are increasing. The applications have > many common parts of > code. Though these applications are separate from > each other they are > run in the same server. > > I heard about CORBA... but also heard that it has > some flaws...like > the programming being very complicated. > Also heard that CORBA is no more used these days... > > Can someone suggest me a better option or is corba > fine? > > Thanks, > Sai > -- > I love Freedom > -- > http://mail.python.org/mailman/listinfo/python-list > From michele.simionato at gmail.com Tue Nov 21 04:14:18 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 21 Nov 2006 01:14:18 -0800 Subject: class method vs static method In-Reply-To: <1164098781.577358.90850@j44g2000cwa.googlegroups.com> References: <1164098781.577358.90850@j44g2000cwa.googlegroups.com> Message-ID: <1164100457.993501.141540@h48g2000cwc.googlegroups.com> Chris Brat wrote: > Hi, > > I've done some reading up but I cant get my head around how/why class > methods can be used as apposed to static methods. > > Can anyone give an example of where they have used class methods? > > Thanks, > Chris Class methods are typically used as factories: class MyClass(object): @classmethod def myfactory(cls): self = cls() initialize(self) return self With different factories you can obtain instances of the same classes initialized in different ways. This is probably better than writing a lot of subclasses with different __init__s. This is my typical use case, but I am sure others will post many other examples of application. Michele Simionato From flamesrock at gmail.com Mon Nov 20 02:16:51 2006 From: flamesrock at gmail.com (flamesrock) Date: 19 Nov 2006 23:16:51 -0800 Subject: secure multiplayer using python? Message-ID: <1164007011.110028.284350@f16g2000cwb.googlegroups.com> How would YOU implement the system described below? -many client program instances connect to a central file+db server -all files on server (this directory) read-only by default to all users, AND public -client mirrors files on central server -each client can 'claim' files on the server, which they have rw access to -over time intervals the client program checks to see if claimed files on the client machine has been modified, and if so uploads to the server, overwriting the old I've heard terms like openssl and pgp thrown around, but how would I implement these in python..? Currently I am handing out ftp user/pass to each client program (hidden from user) which they use for access, but if they mess around with the code, it would be easy to snag this info, then log in and just delete the entire file repository. I would like to keep the ftp implementation, but make it so that users cannot get this information.. but obviously that is impossible. What would you do? What is the most secure way? This will probably be re-written from scratch, so go wild!! -Thanks, flamesrock From pavlovevidence at gmail.com Mon Nov 13 05:59:57 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 13 Nov 2006 02:59:57 -0800 Subject: Python 3000 idea -- + on iterables -> itertools.chain References: <1163385266.824914.265490@b28g2000cwb.googlegroups.com> Message-ID: <1163415597.022620.153310@b28g2000cwb.googlegroups.com> Georg Brandl wrote: > What has a better chance of success in my eyes is an extension to yield > all items from an iterable without using an explicit for loop: instead of > > for item in iterable: > yield item > > you could write > > yield from iterable > > or > > yield *iterable Since this is nothing but an alternate way to spell a very specific (and not-too-common) for loop, I expect this has zero chance of success. Carl Banks From gabor at nekomancer.net Sun Nov 19 15:06:51 2006 From: gabor at nekomancer.net (gabor) Date: Sun, 19 Nov 2006 21:06:51 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: <455E5D15.7030207@v.loewis.de> References: <18c54$455d019b$59ad1aca$24364@news.flashnewsgroups.com> <455d507d$0$18480$9b622d9e@news.freenet.de> <3188c$455d923f$59ad1aca$4742@news.flashnewsgroups.com> <455E5D15.7030207@v.loewis.de> Message-ID: <3e540$4560b958$59ad1aca$32456@news.flashnewsgroups.com> Martin v. L?wis wrote: > gabor schrieb: >> depends on the application. in the one where it happened i would just >> display an error message, and tell the admins to check the >> filesystem-encoding. >> >> (in other ones, where it's not critical to get the correct name, i would >> probably just convert the text to unicode using the "replace" behavior) >> >> what about using flags similar to how unicode() works? strict, ignore, >> replace and maybe keep-as-bytestring. >> >> like: >> os.listdir(dirname,'strict') >> >> i know it's not the most elegant, but it would solve most of the >> use-cases imho (at least my use-cases). > > Of course, it's possible to implement this on top of the existing > listdir operation. > > def failing_listdir(dirname, mode): > result = os.listdir(dirname) > if mode != 'strict': return result > for r in result: > if isinstance(r, str): > raise UnicodeDecodeError > return result > yes, sure... but then.. it's possible to implement it also on top of an raise-when-error version :) so, what do you think, how should this issue be solved? currently i see 2 ways: 1. simply fix the documentation, and state that if the file-name cannot be decoded into unicode, then it's returned as byte-string. but that also means, that the typical usage of: [os.path.join(path,n) for n in os.listdir(path)] will not work. 2. add support for some unicode-decoding flags, like i wrote before 3. some solution. ? gaobr From phd at phd.pp.ru Sat Nov 18 14:08:22 2006 From: phd at phd.pp.ru (Oleg Broytmann) Date: Sat, 18 Nov 2006 22:08:22 +0300 Subject: [Zopyrus] A python IDE for teaching that supports cyrillic i/o In-Reply-To: <20061118190104.GA29614@58sirius016.dc.ukrtel.net> References: <20061118190104.GA29614@58sirius016.dc.ukrtel.net> Message-ID: <20061118190822.GB19739@phd.pp.ru> On Sat, Nov 18, 2006 at 09:01:04PM +0200, Kirill Simonov wrote: > Could anyone suggest me a simple IDE suitable for teaching Python as a > first programming language to high school students? Does it have to be an IDE? Wouldn't it be better to use a simple text editor + command line? Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From tnleeuw at gmail.com Thu Nov 23 08:36:46 2006 From: tnleeuw at gmail.com (Tim N. van der Leeuw) Date: 23 Nov 2006 05:36:46 -0800 Subject: Porting Tkinter application to JYthon In-Reply-To: References: Message-ID: <1164289006.543874.307110@l12g2000cwl.googlegroups.com> Hi, sandip desale wrote: > Dear All, > > We have a Tcl/Tk application written using Python 2.2. Using this application we want to call some customizable Java APIs. I tried porting Tcl/Tk application to Jython but not able to do the same as TKinter library is not available with JYthon. > > Can you please help me in porting Tkinter application to Jython? Also kindly let me know how to do the same. Not having Tkinter in Jython, you can either rewrite your app to be a Java Swing app, or you can embed the Java JVM into the Python interpreter as an importable library. I believe some projects exist to enable the latter, although I don't know of a URL. Cheers, --Tim > > > Thanks & Regards, > Sandip Desale > > > -- > > Search for products and services at: > http://search.mail.com From skip at pobox.com Sun Nov 12 15:56:49 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 12 Nov 2006 14:56:49 -0600 Subject: Random image text generation? In-Reply-To: References: Message-ID: <17751.35473.578283.979433@montanaro.dyndns.org> >> Is there a module out there that will generate an image with a random >> text string such as the confirmation images you see on various >> websites? Mitja> They're called captcha images or captchas for short. Googling Mitja> for "python captcha" returns several hits; see what you like... Thanks. I'd never heard that term before. Assuming I can get PIL installed with freetype support on my Mac the ASPN recipe looks like it will do the trick. Skip From apardon at forel.vub.ac.be Fri Nov 24 05:15:58 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Nov 2006 10:15:58 GMT Subject: locking bsddb objects Message-ID: This is a little project using python 2.3.5, I want to use one of the bsddb objects, but I also need to protect against concurrent access and modification. IMO this would be something for fcntl.flock or fcntl.lockf. However the bsddb objects don't provide a fileno method. So how do I protect against concurrent access and modification? -- Antoon Pardon From jonas.esp at googlemail.com Thu Nov 23 05:46:25 2006 From: jonas.esp at googlemail.com (GinTon) Date: 23 Nov 2006 02:46:25 -0800 Subject: sys.stderr.write and sys.exit Message-ID: <1164278785.075748.220690@j44g2000cwa.googlegroups.com> Is the same use _sys.stderr.write('error message'); sys.exit(1)_ than _sys.exit('error message')_ ? Note: help(sys.exit) If the status is omitted or None, it defaults to zero (i.e., success). If the status is numeric, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure). From fredrik at pythonware.com Sun Nov 19 15:18:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Nov 2006 21:18:19 +0100 Subject: ElementTree: namespace declaration in each element? In-Reply-To: <1163966482.662827.99010@k70g2000cwa.googlegroups.com> References: <1163939038.754792.48730@e3g2000cwe.googlegroups.com> <1163966482.662827.99010@k70g2000cwa.googlegroups.com> Message-ID: cyberco wrote: > OK, that's what I was already doing. Thanks. > Will the standard serializer in 1.3 support default namespaces? that's the plan. I've been working on a more modular XML writer, which will make it easier to tweak the output in various ways, without having to write everything from scratch. From filipwasilewski at gmail.com Sat Nov 18 09:31:40 2006 From: filipwasilewski at gmail.com (Filip Wasilewski) Date: 18 Nov 2006 06:31:40 -0800 Subject: numpy: frequencies References: Message-ID: <1163860300.030311.100110@j44g2000cwa.googlegroups.com> robert wrote: > I have an integer array with values limited to range(a,b) like: > > ia=array([1,2,3,3,3,4,...2,0,1]) > > and want to speedly count the frequencies of the integers into get a density matrix. > Is this possible without looping? See numpy.bincount (for integers >= 0) if you mean 'without writing looping code in Python' or please specify your question. > Question 2: is it possible to compute a "moving maximum" without python looping > > ia=array([4,2,1,5,3,2,2,0,1,1]) > -> mvmax(ia,3) -> > [4,4,4,5,5,5,3,2,2,1]) I haven't seen a ready solution but this can be easily converted into Pyrex/C looping. cheers, fw From jonas.esp at googlemail.com Tue Nov 21 09:25:45 2006 From: jonas.esp at googlemail.com (MindClass) Date: 21 Nov 2006 06:25:45 -0800 Subject: Load objects using __import__ In-Reply-To: <1164117880.843179.24210@h54g2000cwb.googlegroups.com> References: <1164114886.356071.14990@k70g2000cwa.googlegroups.com> <1164117880.843179.24210@h54g2000cwb.googlegroups.com> Message-ID: <1164119145.452650.315340@f16g2000cwb.googlegroups.com> Indeed before reading your message I solved it doing: model_name = Country mod = eval('i18n_module.%s' % model_name) c1 = mod(name="Afghanistan") exec c1 but I'll use getattr as you say. Thanks Carl Banks ha escrito: > MindClass wrote: > > But when I load the object I get > > SyntaxError: invalid syntax > > > > c1 = > '/home/lala/django/project/I18n/models.pyc'>.Country(name="Afghanistan") > > It looks like you're running generated code somewhere, but passing the > module itself rather than the name of the module to the code generator > by mistake. Perhaps you're execing some code that you pass the module > name to? Something like this? > > exec 'c1 = %s.Country(name="Afgahanstan")' % module_name > > You seem to be erroneously using the module itself, not the module > name. > > That's about all I can help without more information. > > > P.S. if you are doing that, consider using getattr instead of exec. > > c1 = getattr(module,Country)(name="Afgansitan") > > > Carl Banks From steve at holdenweb.com Fri Nov 17 10:08:35 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 17 Nov 2006 15:08:35 +0000 Subject: Secure Python In-Reply-To: <001501c70a50$440b4840$03000080@hendrik> References: <455c1665@quokka.wn.com.au><455c4d9b@quokka.wn.com.au> <001501c70a50$440b4840$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Stephan Kuhagen" wrote: > > >> The problem with linux kernel limits are, that they won't work really good >> on MacOSX and Windows... OTOH the idea is the right one, but the effect can >> be achieved inside of Python. Since Python does byte compile the code and >> the interpreter evaluates each byte code token in one evaluation step. The >> interpreter could be extended for such usecases to count and limit the >> number of evaluation steps allowed for untrusted script or methods in >> untrusted script as well as to limit the recursion depth or memory to be >> allocated. All those limits are managed by the interpreter for script code >> and hence can be limited for untrusted code by the interpreter. This also >> does not really make DoS impossible (what about C extensions? - maybe >> restricting "import"?). - As I said before in this thread, making a sandbox >> really secure is a hard job, and may need some serious changes in the >> Python interpreter, but AFAIK from Tcl, it is possible - and would be nice >> to have. > > I seem to recall previous discussion on this group about a thing called the > bastion module, > and that it was deprecated. Not sure if it has any relevance. > Anyone with an interest in secure Python should take a look at what Brett Cannon is doing in his postgraduate work. There have been some discussions on the python-dev list. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From amitsoni.1984 at gmail.com Fri Nov 24 17:08:18 2006 From: amitsoni.1984 at gmail.com (amitsoni.1984 at gmail.com) Date: 24 Nov 2006 14:08:18 -0800 Subject: Installing CVXOPT Message-ID: <1164406098.224855.157120@f16g2000cwb.googlegroups.com> hi, how can I install and start using CVXOPT. I have python 2.5 version installed. what else do i need to download and install for CVXOPT. thanks amit From gagsl-py at yahoo.com.ar Sat Nov 25 00:56:47 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 25 Nov 2006 02:56:47 -0300 Subject: Simple threading In-Reply-To: <1164295697.757788.26710@e3g2000cwe.googlegroups.com> References: <1164295697.757788.26710@e3g2000cwe.googlegroups.com> Message-ID: <7.0.1.0.0.20061125024927.01cf0690@yahoo.com.ar> At Thursday 23/11/2006 12:28, jrpfinch wrote: >I'm just getting started on threading and was wondering why the >following code does not work (i know globals is bad style - I'll >eliminate them eventually). All I get is a blank cursor flashing. You've got your example already working. Globals are bad style, but worse, threads and globals don't mix very well: you need some sort of syncronization for accessing globals (specially for writing them). >class ImapThread(threading.Thread): > def run(self): > global g_currenttick > if time.time() > (g_datum + (g_secondspertick * >g_currenttick)): > print "Ticked %s" % g_currenttick > g_currenttick=g_currenttick+1 > print g_currenttick Having more than one thread, g_currenttick could have been modified *after* you read its value and *before* you write it back, so you lose the count. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From fredrik at pythonware.com Tue Nov 28 10:48:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 28 Nov 2006 16:48:16 +0100 Subject: Inheritance from builtin list and override of methods. In-Reply-To: <1164727886.491487.176840@j72g2000cwa.googlegroups.com> References: <200611261804.54669.mgiann@beta-cae.gr> <200611271133.48359.mgiann@beta-cae.gr> <1164727886.491487.176840@j72g2000cwa.googlegroups.com> Message-ID: Carl Banks wrote: > Because the concerns of thousands of legitimate programmers who want > good performance out of their sorts outweigh the concerns of the one or > two hax0r d00ds who think it would be cool to hook into sort internals. ... and haven't yet realized that using sorted() and converting back from the resulting list will outperform *any* solution they can come up with themselves. From korvus at gmail.com Thu Nov 16 21:21:51 2006 From: korvus at gmail.com (Jeff Poole) Date: 16 Nov 2006 18:21:51 -0800 Subject: cPickle problems In-Reply-To: References: <1163722893.992949.295350@b28g2000cwb.googlegroups.com> <1163723175.530850.185990@m73g2000cwd.googlegroups.com> <1163724509.572724.199720@f16g2000cwb.googlegroups.com> Message-ID: <1163730111.641857.142850@k70g2000cwa.googlegroups.com> Good idea. Well, I did that, and I found out that the object causing problems is a ParseResults object (a class from PyParsing) and that the __getstate__ member is in fact an empty string (''). I'm not sure where this leaves me... The PyParsing code clearly never creates such a member and my code never creates it. In fact, searching all the code involved (not including what is in /usr/lib/python2.4 ), shows no use of __getstate__ at all (or even the string "getstate"). Ok, I figured it out. ParseResults has the following member: def __getattr__( self, name ): if name not in self.__slots__: if self.__tokdict.has_key( name ): if name not in self.__accumNames: return self.__tokdict[name][-1][0] else: return ParseResults([ v[0] for v in self.__tokdict[name] ]) else: return "" return None So when something tries to retrieve .__getstate__, it returns an empty string. If I tell it to raise an AttributeException instead, then I get this message: TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled I think I need to talk to the author of PyParsing about this one... Thanks for your help! Jeff > Someway, self.__getstate__ is a string, not a method... > Since it fails inside a python module, you could print some debug > information to see what happens, like repr(self), type(self), repr(getstate)... > > > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! > ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From steve at holdenweb.com Mon Nov 13 15:27:22 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Nov 2006 14:27:22 -0600 Subject: jython's future In-Reply-To: <4558BB29.4020002@gmail.com> References: <1163425734.640509.99420@m73g2000cwd.googlegroups.com> <1163433118.770742.262140@e3g2000cwe.googlegroups.com> <4rrjenFspqicU2@mid.uni-berlin.de> <4558ACAC.1030001@web.de> <1163440390.3434.45.camel@dot.uniqsys.com> <4558BB29.4020002@gmail.com> Message-ID: <4558D52A.3090109@holdenweb.com> ?ukasz Langa wrote: > Steve Holden: >> I think you will find that most of Fredrik Lundh's stuff will work on >> 1.5.2. He sets a fine example to us all. >> > > 1.5.2? Come on, it's 7 years old. Back then PHP was still at 3.0, Java > was at 1.2 (and compiling Hello World took over 5 minutes), Google was > nothing more than a search engine (still Beta at the time!). > > What do we have all these cool new language features for if it's > considered bad behaviour to actually use them? > > OK, I see the point in being compatible with Python 2.1 (well, maybe 2.2 > with new-style classes and __descriptors__), just like it's still useful > to be Java 1.4 compatible and PHP 4 compatible. > > But Python 1.5.2? From the official site: "*Do yourself a favor* and get > a more recent version!" ;-) It doesn't even have string methods. Today > Python 1.5.2 is being implemented on one-chip GSM modules ( > http://www.telit.co.it/product.asp?productId=96 ). And yes, it actually > works quite well there :-) > And thanks to Fredrik there's a chance you'll be able to use PIL there. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Roberto.Bonvallet at cern.ch Tue Nov 14 09:38:37 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Tue, 14 Nov 2006 14:38:37 +0000 (UTC) Subject: Programmatically finding "significant" data points References: <1163513101.580610.151420@b28g2000cwb.googlegroups.com> Message-ID: erikcw wrote: > I have a collection of ordered numerical data in a list. The numbers > when plotted on a line chart make a low-high-low-high-high-low (random) > pattern. I need an algorithm to extract the "significant" high and low > points from this data. In calculus, you identify high and low points by looking where the derivative changes its sign. When working with discrete samples, you can look at the sign changes in finite differences: >>> data = [...] >>> diff = [data[i + 1] - data[i] for i in range(len(data))] >>> map(str, diff) ['0.4', '0.1', '-0.2', '-0.01', '0.11', '0.5', '-0.2', '-0.2', '0.6', '-0.1', '0.2', '0.1', '0.1', '-0.45', '0.15', '-0.3', '-0.2', '0.1', '-0.4', '0.05', '-0.1', '-0.25'] The high points are those where diff changes from + to -, and the low points are those where diff changes from - to +. HTH, -- Roberto Bonvallet From JKPeck at gmail.com Mon Nov 13 09:23:23 2006 From: JKPeck at gmail.com (JKPeck) Date: 13 Nov 2006 06:23:23 -0800 Subject: Character Encodings and display of strings Message-ID: <1163427803.150232.221030@f16g2000cwb.googlegroups.com> I am trying to understand why, with nonwestern strings, I sometimes get a hex display and sometimes get the string printed as characters. With my Python locale set to Japanese and with or without a # coding of cp932 (this is Windows) at the top of the file, I read a list of Japanese strings into a list, say, catlis. With this code for item in catlis: print item print catlis print " ".join(catlis) the first print (print item) displays Japanese text as characters.. The second print (print catlis) displays a list with the double byte characters in hex notation. The third print (print " ".join(catlis)) prints a combined string of Japanese characters properly. According to the print documentation, "If an object is not a string, it is first converted to a string using the rules for string conversions" but the result is different with a list of strings. The hex display looks like this: ['id', '\x90\xab\x95\xca', '\x90\xb6\x94N\x8c\x8e\x93\xfa', '\x8fA\x8aw\x94N\x90\x94', '\x90E\x8e\xed', '\x8b\x8b\x97^', '\x8f\x89\x94C\x8b\x8b', '\x8d\xdd\x90\xd0\x8c\x8e\x90\x94', '\x90E\x96\xb1\x8co\x97\xf0', '\x90l\x8e\xed'] and correctly shows the hex values of the Japanese characters. Why are these different? TIA, Jon Peck From rupole at hotmail.com Tue Nov 28 07:47:48 2006 From: rupole at hotmail.com (Roger Upole) Date: Tue, 28 Nov 2006 07:47:48 -0500 Subject: Accessing file metadata on windows XP References: <1164704134.100569.101270@j72g2000cwa.googlegroups.com> Message-ID: <1164718278_34797@sp6iad.superfeed.net> wrote in message news:1164704134.100569.101270 at j72g2000cwa.googlegroups.com... > When rightclicking a, for example, pdf file on windows, one normally > gets a screen with three or four tags. Clicking on one of the summary > tag one can get some info like "title", "Author", "category", "keyword" > etc.. > > My question is how can I programmatically read and change these data > with python. I know I should use Hammond's win32 extension, somehow > involving the pythoncom, storagecon of win32com etc.. Unfortunately, > so far I cannot get anything useful. Instead of trying blindly, would > somebody please points me to the correct direction. A little snippet > would help. I am particular interested in pdf files. > See \win32com\test\testStorage.py for an example of using the storage interfaces to read and write document summary info. Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From no-spam at no-spam-no-spam.invalid Wed Nov 29 13:19:07 2006 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 29 Nov 2006 19:19:07 +0100 Subject: Detecting recursion loops In-Reply-To: <1164813771.171053.93190@j44g2000cwa.googlegroups.com> References: <1164813771.171053.93190@j44g2000cwa.googlegroups.com> Message-ID: Rob Wolfe wrote: > robert wrote: >> My code does recursion loops through a couple of functions. Due to problematic I/O input this leads sometimes to "endless" recursions and after expensive I/O to the Python recursion exception. >> What would be a good method to detect recursion loops and stop it by user-Exception (after N passes or some complex criteria) without passing a recursion counter parameter through all the funcs? > > What about `sys.setrecursionlimit`? > > http://docs.python.org/lib/module-sys.html That is a low level barrier. I just want to limit a certain recursion call chain. From lowz06 at gmail.com Sun Nov 19 17:32:45 2006 From: lowz06 at gmail.com (John (Z R) L) Date: 19 Nov 2006 14:32:45 -0800 Subject: How do I stop Python IDLE (GUI) from immediately exiting when I enter it? In-Reply-To: References: <1163921048.878108.145810@j44g2000cwa.googlegroups.com> Message-ID: <1163975565.887782.93050@h48g2000cwc.googlegroups.com> Thanks for the replies so far. I do exactly what that website says, and on the old computer (Windows 98), I click run module and nothing happens. No text gets displayed on my IDLE. It contained that firewall message at the top. Back on the new computer, I deleted all of my .py files and I could go back to the Python IDLE (GUI) again. But my problem is with that when I run this module: "a = 1 print a a = a + 1 print a a = a * 2 print a" , the "1 2 4" appears on the screen, but the program doesn't end. You don't get a new ">>>" like when you finish running all the other modules. So when I want to run other modules, it says: "The Python Shell Window is already executing a command; please wait until it is finished." Note that all of my modules don't need any "end" at the last line, nor do I need "raw_input" to end the program. How do I make it so this module ends without using the word "end" because it would exit the entire IDLE Shell? From craigtw.online at gmail.com Sun Nov 26 18:17:58 2006 From: craigtw.online at gmail.com (Craig) Date: 26 Nov 2006 15:17:58 -0800 Subject: Generating header information using ElementTree References: <1164574832.936947.69420@h54g2000cwb.googlegroups.com> <1164579522.671325.36260@14g2000cws.googlegroups.com> <4suidqF10rlh1U1@mid.uni-berlin.de> Message-ID: <1164583078.233238.227010@45g2000cws.googlegroups.com> Diez B. Roggisch wrote: > Craig schrieb: > > Fredrik Lundh wrote: > > > >> Craig wrote: > >> > >>> I'm only new to Python so please bear with me. I using ElementTree to > >>> generate an XML file that will reference a DTD and an XSL file. The > >>> header information I want at the start of the file is as follows: > >>> > >>> > >>> > >>> > >>> > >>> How do you add this header information to the tree > >> to the file, you mean? use print. > >> > >> > > > > Thanks for the quick response. Here is the code I am using to manually > > write to the file is: > > > > outFile = open("record.xml", 'w') > > outFile.write = ("\n") > > outFile.write = (" > href=\"test.xsl\"?>\n") > > outFile.write = ("\n") > > outFile.close() > > > > When I run the code I get the following error message: > > > > Traceback (most recent call last): > > File "bob-xml.py", line 189, in > > main() > > File "bob-xml.py", line 173, in main > > outFile.write = ("\n") > > AttributeError: 'file' object attribute 'write' is read-only > > > > What am I doing wrong here? If anyone could help that would be > > appreciated. Thanks again. > > write is a method, not a property. > > outFile.write("whatever") > > is the way to go... > > Diez Great. Got that sorted. The problem I have now is that some of the XML data is not copied across to the file when I have the text information included. The number of characters that is lost is equal to the number of characters that is in the block of text I entered before. The code I am using is: def WriteXMLRecord ( record, XMLFileBaseName, root): RecordName = SubElement(root, "Log") #iterate through all the fields in the record for key in record: # write the key and its data test = SubElement(RecordName, key) test.text = str(record[key]) tree = ElementTree(root) tree.write(XMLFileBaseName) def main(): outFile = open("record.xml", 'w') outFile.write(""" \n\n""") root = Element("Log") WriteXMLRecord(data1, "record.xml", root) WriteXMLRecord(data2, "record.xml", root) WriteXMLRecord(data3, "record.xml", root) outFile.close() Any help would be appreciated. Thanks and good luck. Craig From shuanyu at gmail.com Thu Nov 16 02:59:53 2006 From: shuanyu at gmail.com (many_years_after) Date: 15 Nov 2006 23:59:53 -0800 Subject: How to make a python file to a DLL? Message-ID: <1163663993.261179.146630@m7g2000cwm.googlegroups.com> Any solution? Thanks. From arkanes at gmail.com Wed Nov 22 09:49:28 2006 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 22 Nov 2006 08:49:28 -0600 Subject: PyQt app in seperate thread In-Reply-To: <1164206635.601219.36860@j44g2000cwa.googlegroups.com> References: <1164199026.728638.180000@j44g2000cwa.googlegroups.com> <1164204404.675906.59020@b28g2000cwb.googlegroups.com> <1164206635.601219.36860@j44g2000cwa.googlegroups.com> Message-ID: <4866bea60611220649t3a34d02as5f5a578d85420e07@mail.gmail.com> On 22 Nov 2006 06:43:55 -0800, anders wrote: > > Phil Thompson wrote: > > On Wednesday 22 November 2006 2:06 pm, anders wrote: > > > Phil Thompson wrote: > > > > On Wednesday 22 November 2006 12:37 pm, anders wrote: > > > > > I am writing a plugin for a piece of software in python, and I want to > > > > > start up a PyQt GUI in the plugin, without stalling the main thread > > > > > while the gui is running (later i will want to pass messages between > > > > > the main thread and the gui thread). > > > > > > > > > > I'm new to pyqt, so I'm probably doing something very silly, but for > > > > > the moment I'm just trying to get the first pyqt tutorial example > > > > > running in a seperate thread: > > > > > > > > > > ----8<-------- > > > > > > > > > > import sys > > > > > from PyQt4 import QtGui > > > > > from PyQt4 import QtCore > > > > > > > > > > class MyThread( QtCore.QThread ): > > > > > def __init__( self ): > > > > > QtCore.QThread.__init__( self ) > > > > > > > > > > def run( self ): > > > > > app = QtGui.QApplication( sys.argv ) > > > > > hello = QtGui.QPushButton( 'Hello world!' ) > > > > > hello.resize( 500, 500 ) > > > > > hello.show() > > > > > app.exec_() > > > > > QtCore.QThread.terminate( ) > > > > > > > > > > > > > > > > > > > > mt = MyThread() > > > > > mt.start() > > > > > print 'Main thread continuing...' > > > > > mt.wait() > > > > > print 'GUI thread finished.' > > > > > > > > > > ----8<-------- > > > > > > > > > > The app starts up (with a warning WARNING: QApplication was not created > > > > > in the main() thread. ). I get a window, but no button, and clicking on > > > > > the close button does nothing and I have to force the program to quit. > > > > > > > > > > There's got to be a way to get this working, right? Can anyone help me > > > > > along the right path? > > > > > > > > Read http://doc.trolltech.com/4.2/threads.html > > > > > > > > In particular the bit that says that exec_() must be called from the main > > > > thread and not from a QThread. > > > > > > > > Phil > > > > > > OK so that's all good... so how do I go about doing what I want then? > > > Can I set up a window in the second thread and start its event loop > > > without running the event loop in the core app? > > > > No. Read the second sentence of the paragraph I referred to. Also read the > > section "QObject Reentrancy". > > > > Phil > > OK I see that now. Thanks for pointing that out. So basically, I can't > do what I want at all. That's a bit of a pain. Is there no way of > tricking Qt into thinking I'm running it in the main thread? > It's possible with hackery from C++ but I seriously doubt you can do it from PyQt. > A > > -- > http://mail.python.org/mailman/listinfo/python-list > From sjmachin at lexicon.net Sat Nov 18 17:49:31 2006 From: sjmachin at lexicon.net (John Machin) Date: 18 Nov 2006 14:49:31 -0800 Subject: syntax error in sum(). Please explicate. In-Reply-To: References: Message-ID: <1163890171.877239.167310@h54g2000cwb.googlegroups.com> Michael Press wrote: > I have not written python codes nor run any. I saw this > code posted and decided to try it. It fails. I read the > tutorial and the entry for the built in function sum, > but still do not see the problem. The code was cut and > paste. I doubt it -- "none" should be "None" Please help. Thanks. > > _________________________BEGIN_CODE_________________________ > #!/usr/bin/python > > ps = [none, 2,3,5,7,11,13,17,19,23,29] > > def phi(x, a): > return x - sum(phi(x // ps[i+1], i) for i in range(a)) > > def pi(n): > from math import sqrt > if n <= 1: > return 0 > a = pi(int(sqrt(n))) > return phi(n, a) + a - 1 > __________________________END_CODE__________________________ > > Here is the result of running it: > > File "/Users/mdp/source/prime_counter_python", line 6 > return x - sum(phi(x // ps[i+1], i) for i in range(a)) > ^ > SyntaxError: invalid syntax > > Here are some lines from python -v: > > Python 2.3 (#1, Sep 13 2003, 00:49:11) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information New syntax. Python 2.3 is *two* versions behind the current production version. Either (a) run it on Python 2.4 or 2.5 or (b) enclose the argument to sum in square brackets i.e. sum([blah blah blah]) instead of sum(blah blah blah) Cheers, John From fredrik at pythonware.com Wed Nov 22 02:42:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Nov 2006 08:42:23 +0100 Subject: Misleading IOerror when opening a non-existent file for append? In-Reply-To: <1164037095.148334.157670@e3g2000cwe.googlegroups.com> References: <1164037095.148334.157670@e3g2000cwe.googlegroups.com> Message-ID: jkn wrote: > This 'invalid mode: a' error message seems weird to me. Is this a bug > or am I missimg something? It depends on the underlying implementation of fopen(), which, on some platforms, doesn't set the right error code for bad mode strings. Python uses some simple heuristics to try to get around this (earlier versions could give "error: no error" for this case), but they're not always able to do the right thing. From http Sat Nov 25 05:29:41 2006 From: http (Paul Rubin) Date: 25 Nov 2006 02:29:41 -0800 Subject: The Python Papers Edition One References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <7xodqyn5kd.fsf@ruckus.brouhaha.com> <1164323350.988946.209350@l12g2000cwl.googlegroups.com> <1164340388.885058.264750@l12g2000cwl.googlegroups.com> Message-ID: <7x7ixjn7je.fsf@ruckus.brouhaha.com> "tleeuwenburg at gmail.com" writes: > I thought I just had. In what way does the statement "Yes, it's true > that you can't resell copies of The Python Papers for personal profits, > but you may derive from it, reproduce and propagate it" not provide > such a revision and clarification? Seriously, let me know what exact > statement you feel needs to be made, and I will endorse it accordingly > if it is accurate. You should not use the phrase "free as in freedom". "Free as in beer" is more accurate for the NC licenses. > For my part, I don't see that there are ethically serious restrictions > on the freedom of use of the information contained within The Python > Papers. There is a big rant against the CC-NC licenses on Kuro5hin: http://www.kuro5hin.org/story/2005/9/11/16331/0655 > Call it "mostly free" if you like. That is reasonable and if you're going to stick with the NC license, it would be cool if you also were to descibe TPP as "mostly free", or maybe "gratis" (as opposed to "libre") in your descriptions. "Gratis" is sometimes translated "free as in beer", in contrast with "free as in speech" or "free as in freedom". > There's no such thing as complete > freedom of information anyway, and we have done the best we can. Well, others including the Wikimedia projects (which use GFDL) and the PLoS journals (www.plos.org) (which use CC-BY) go further than you do, so "we have done the best we can" sounds like an apology that "the best you can" wasn't up to the level that those other, much more significant projects have managed to do. Should you expect a response other than "oh well, nice try"? One of my desires as a free software user, for example, is to be able to buy a new computer with a complete suite of software preinstalled on the hard disk, including all the needed apps, development tools, and documentation and source code for everything, and the freedom to propagate it all in the same way. All the GNU/Linux stuff and all the Python.org stuff, plus more general reference works like Wikipedia, educational materials like Wikibooks, and scientific journals like PLOS, are licensed in ways that would permit including it with such a computer. It even includes some entertainment media like various music downloads from Jamendo and the non-NC CC movies. But your journal would have to be omitted. > We considered releasing under the GPL, but felt that we wanted to > preserve two things which don't seem to be provided by it: > * Rights of the author to attribution as may be expected and desired > of an academic publication. The GPL doesn't seem appropriate for > disseminating the work of a single author. > * Rights of the author to have their words presented I would have suggested the GNU Free Documentation License (GFDL) that Wikipedia uses, but that's just me. > * Opportunity for the author to commercially license their works to > other vendors. By choosing the Share Alike restriction, we have > encouraged the free dissemination of research information without > affecting its commercial use. Right, the effect on commercial use comes from the NC restriction, not the SA restriction. > * Rights of the author to have their words presented I'm not sure what you're getting at but if you mean no modified versions, you need -ND for that. > It seemed to be the best middle ground between taking a strong > ideological position on either side that would be bound to put > people off side. It preserves some rights for the author while still > allowing a substantial amount of free re-use. "Middle grounds" often combine the disadvantages of both "endpoints". And failing to take a strong position can leave you in a weak one. > * Reputation as an > unbiased, financially disinterested group. The NC licenses withhold some rights for exclusive use by the initial publisher, releasing only a subset to users. That is usually not a sign of disinterest. For example, Cory Doctorow's novels are published under NC licenses, which he says is working for him as a marketing tool. But he has a clear and undisguised financial interest in choosing the NC license. > By distributing under the > license we chose, we hoped to establish our credentials. Well, it seems to me that you're putting out yet another non-libre publication, it's nice that it's gratis but I don't think it helps establish credentials with FOSS users and the confusion so far may actually be hurting. > Your email indicates a possible concern that we are doing something > untoward -- this was not at all intended, nor is it true. As mentioned in another post, I feel that you're (perhaps unintentionally) trying to attach to your publication the good associations created by the licensing practices of the FOSS movement, while not actually following those practices. "Untoward" might be a slightly overstrong term, however, you are creating confusion and maybe suffering from it yourself. Here is the issue: people who write FOSS code and documentation often make sacrifices (of their free time, or of potential revenue) in order to do so. They are aware of those sacrifices and make them anyway. So it's a bit grating to those of us who work on FOSS projects (or even just admire them) when someone comes along and tries (even unintentionally) to attach to themselves the recognition comes from those sacrifices, without actually making the same sacrifices. That may explain the reaction you're getting. From martin.laloux at gmail.com Thu Nov 16 07:26:49 2006 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: 16 Nov 2006 04:26:49 -0800 Subject: Tkinter & Python 2.5 Problems on MAC OS 10.3.9 In-Reply-To: References: Message-ID: <1163680008.909233.195910@h48g2000cwc.googlegroups.com> which distribution of python you use ? I use the one of http://pythonmac.org/packages/py25-fat/index.html withoutproblem From news1 at bayerf.de Sat Nov 25 09:53:30 2006 From: news1 at bayerf.de (Fred Bayer) Date: Sat, 25 Nov 2006 15:53:30 +0100 Subject: Ruby/Python/REXX as a MUCK scripting language In-Reply-To: <2006112418112116807-zobeid@techiecom> References: <2006112418112116807-zobeid@techiecom> Message-ID: <4sr3neF111j0gU1@mid.individual.net> Tony Belding wrote: > I'm interested in using an off-the-shelf interpreted language as a > user-accessible scripting language for a MUCK. I'm just not sure if I > can find one that does everything I need. The MUCK must be able to call > the interpreter and execute scripts with it, but the interpreter must > also be able to call functions in the MUCK code. And then there's the > security issue that really worries me. . . I have to be able to limit > what the interpreter can execute. I can't have my users running scripts > that access the console, access the filesystem or sockets directly, or > call libraries or other binaries outside the MUCK. > > Is this practical? I'm thinking of Ruby or Python for this, if they can > meet the requirements. > Don't forget Lua: www.lua.org It fulfills your requirements and is easily embedable. From ronrsr at gmail.com Mon Nov 13 14:51:51 2006 From: ronrsr at gmail.com (ronrsr) Date: 13 Nov 2006 11:51:51 -0800 Subject: Printing database output in tabular form In-Reply-To: References: <1163446803.990020.112810@i42g2000cwa.googlegroups.com> Message-ID: <1163447511.497564.40740@b28g2000cwb.googlegroups.com> On Nov 13, 2:48 pm, Fredrik Lundh wrote: > ronrsr wrote: > > when I try to print a web table containing output from a database, I am > > getting more info than I want- - > > > I would like this to print w'o the array('c',arrays instead of strings? what database is this, and how is that > column defined ? > > It is a MySQL database - those columns are defined as BLOBs bests, -rsr- From paddy3118 at netscape.net Wed Nov 15 09:20:27 2006 From: paddy3118 at netscape.net (Paddy) Date: 15 Nov 2006 06:20:27 -0800 Subject: multi split function taking delimiter list In-Reply-To: <1163573899.153057.242510@f16g2000cwb.googlegroups.com> References: <1163534200.476392.303680@m73g2000cwd.googlegroups.com> <1163541478.391883.227320@e3g2000cwe.googlegroups.com> <1163573899.153057.242510@f16g2000cwb.googlegroups.com> Message-ID: <1163600427.874213.41340@b28g2000cwb.googlegroups.com> Paddy wrote: > Paddy wrote: > > > martinskou at gmail.com wrote: > > > > > Hi, I'm looking for something like: > > > > > > multi_split( 'a:=b+c' , [':=','+'] ) > > > > > > returning: > > > ['a', ':=', 'b', '+', 'c'] > > > > > > whats the python way to achieve this, preferably without regexp? > > > > > > Thanks. > > > > > > Martin > > > > I resisted my urge to use a regexp and came up with this: > > > > >>> from itertools import groupby > > >>> s = 'apple=blue+cart' > > >>> [''.join(g) for k,g in groupby(s, lambda x: x in '=+')] > > ['apple', '=', 'blue', '+', 'cart'] > > >>> > > > > For me, the regexp solution would have been clearer, but I need to > > stretch my itertools skills. > > > > - Paddy. > Arghhh! > No colon! > Forget the above please. > > - Pad. With colon: >>> from itertools import groupby >>> s = 'apple:=blue+cart' >>> [''.join(g) for k,g in groupby(s,lambda x: x in ':=+')] ['apple', ':=', 'blue', '+', 'cart'] >>> - Pad. From tech at axetic.com Thu Nov 23 06:23:29 2006 From: tech at axetic.com (Tech) Date: Thu, 23 Nov 2006 12:23:29 +0100 Subject: "10, 20, 30" to [10, 20, 30] In-Reply-To: <1164280390.745628.167770@k70g2000cwa.googlegroups.com> References: <1164280390.745628.167770@k70g2000cwa.googlegroups.com> Message-ID: <456584ac$0$5085$ba4acef3@news.orange.fr> Daniel Austria a ?crit : > Sorry, > > how can i convert a string like "10, 20, 30" to a list [10, 20, 30] > > what i can do is: > > s = "10, 20, 30" > tmp = '[' + s + ']' > l = eval(tmp) > > but in my opinion this is not a nice solution > > > daniel > If you're sure that there's only ints l = [int(item) for item in s.split(', ')] Yannick From fredrik at pythonware.com Wed Nov 29 11:35:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Nov 2006 17:35:05 +0100 Subject: Overloading "if object" unary operator In-Reply-To: <1164817022.500511.295260@80g2000cwy.googlegroups.com> References: <1164817022.500511.295260@80g2000cwy.googlegroups.com> Message-ID: Sarcastic Zombie wrote: > If I have a class > > class A: > __init__(id) > self.id = id > > is there any way to overload the 'if' unary usage to detect if a > variable has a value? http://effbot.org/pyref/__nonzero__ From gabor at nekomancer.net Fri Nov 17 05:43:09 2006 From: gabor at nekomancer.net (gabor) Date: Fri, 17 Nov 2006 11:43:09 +0100 Subject: os.lisdir, gets unicode, returns unicode... USUALLY?!?!? In-Reply-To: <455d507d$0$18480$9b622d9e@news.freenet.de> References: <18c54$455d019b$59ad1aca$24364@news.flashnewsgroups.com> <455d507d$0$18480$9b622d9e@news.freenet.de> Message-ID: <3188c$455d923f$59ad1aca$4742@news.flashnewsgroups.com> Martin v. L?wis wrote: > gabor schrieb: >> i also recommend this approach. >> >> also, raising an exception goes well with the principle of the least >> surprise imho. > > Are you saying you wouldn't have been surprised if that had been > the behavior? yes, i would not have been surprised. because it's kind-of expected when dealing with input, that malformed input raises an unicode-exception. and i would also expect, that if os.listdir completed without raising an exception, then the returned data is correct. > How would you deal with that exception in your code? depends on the application. in the one where it happened i would just display an error message, and tell the admins to check the filesystem-encoding. (in other ones, where it's not critical to get the correct name, i would probably just convert the text to unicode using the "replace" behavior) what about using flags similar to how unicode() works? strict, ignore, replace and maybe keep-as-bytestring. like: os.listdir(dirname,'strict') i know it's not the most elegant, but it would solve most of the use-cases imho (at least my use-cases). gabor From mauriceling at acm.org Wed Nov 15 18:39:13 2006 From: mauriceling at acm.org (Maurice LING) Date: Wed, 15 Nov 2006 23:39:13 GMT Subject: Python deployment options. In-Reply-To: References: <1162982262.010438.99260@f16g2000cwb.googlegroups.com> <1162985073.163257.110180@m73g2000cwd.googlegroups.com> <1162986129.233443.268730@h54g2000cwb.googlegroups.com> <1162990156.204577.198720@h48g2000cwc.googlegroups.com> Message-ID: <455ba51e$1@news.unimelb.edu.au> Cameron Laird wrote: > In article <1162990156.204577.198720 at h48g2000cwc.googlegroups.com>, > Richard Charts wrote: > . > . > . > >>Well on a Win machine, probably. >>Almost every Linux machine you come across will have (most likely a >>fairly recent build of) python. For Macs, I'm not so sure but it's >>probably closer to Linux than Win. >> > > > Recent releases of Mac OS build in Python. Python has been part of Mac OSX since OSX 10.2 (maybe even earlier but 10.2 is the earliest I've used). ML From bignose+hates-spam at benfinney.id.au Wed Nov 29 17:59:00 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 30 Nov 2006 09:59:00 +1100 Subject: Detecting recursion loops References: <1164815293.529674.109850@l39g2000cwd.googlegroups.com> Message-ID: <87hcwhrhaj.fsf@benfinney.id.au> robert writes: > Carl Banks wrote: > > 2. Consider whether you're unwittingly trying to cover up a bug. > > ISTM no matter how problematic the input is, you should at least > > be able to make progress on it. Are you getting this error > > because, say, you're not incrementing a counter somewhere, and > > thus recalling a function with the same arguments again? > > the "bug" comes in from the I/O input. If a program doesn't gracefully deal with bad input, that's a bug in the program. You should be designing your input handler so that it will do something helpful (even if that's to stop immediately with an informative error message) in the event of bad input, rather than allowing that bad data to send your program into an endless loop. -- \ "People's Front To Reunite Gondwanaland: Stop the Laurasian | `\ Separatist Movement!" -- wiredog, http://kuro5hin.org/ | _o__) | Ben Finney From rald86 at yahoo.fr Thu Nov 30 17:23:11 2006 From: rald86 at yahoo.fr (Robert R.) Date: 30 Nov 2006 14:23:11 -0800 Subject: best way to align words? Message-ID: <1164925391.696612.64860@80g2000cwy.googlegroups.com> Hello, i would like to write a piece of code to help me to align some sequence of words and suggest me the ordered common subwords of them s0 = "this is an example of a thing i would like to have".split() s1 = "another example of something else i would like to have".split() s2 = 'and this is another " example " but of something ; now i would still like to have'.split() ... alist = (s0, s1, s2) result should be : ('example', 'of', 'i', 'would', 'like', 'to', 'have' but i do not know how should i start, may be have you a helpful suggestion? a trouble i have if when having many different strings my results tend to be nothing while i still would like to have one of the, or maybe, all the best matches. best. From paddy3118 at netscape.net Fri Nov 24 11:37:13 2006 From: paddy3118 at netscape.net (Paddy) Date: 24 Nov 2006 08:37:13 -0800 Subject: synching with os.walk() In-Reply-To: <1164385629.462106.106120@j72g2000cwa.googlegroups.com> References: <1164385629.462106.106120@j72g2000cwa.googlegroups.com> Message-ID: <1164386233.446742.67640@f16g2000cwb.googlegroups.com> Paddy wrote: > Andre Meyer wrote: > > > Hi all > > > > os.walk() is a nice generator for performing actions on all files in a > > directory and subdirectories. However, how can one use os.walk() for walking > > through two hierarchies at once? I want to synchronise two directories (just > > backup for now), but cannot see how I can traverse a second one. I do this > > now with os.listdir() recursively, which works fine, but I am afraid that > > recursion can become inefficient for large hierarchies. > > > > thanks for your help > > Andr? > > Walk each tree individually gathering file names relative to the head > of the tree and modification data. > > compare the two sets of data to generate: > 1. A list of what needs to be copied from the original to the copy. > 2. A list of what needs to be copied from the copy to the original > > Do the copying. > > |You might want to show the user what needs to be done and give them > the option of aborting after generating the copy lists. > > - Paddy. P.S. If you are on a Unix type system you can use tar to do the copying as you can easily compress the data if it needs to go over a sow link, and tar will take care of creating any needed directories in the destination if you create new directories as well as new files. - Paddy. From mail at microcorp.co.za Fri Nov 24 01:51:32 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 24 Nov 2006 08:51:32 +0200 Subject: Is time.time() < time.time() always true? References: <1164150625.377064.112550@j44g2000cwa.googlegroups.com> Message-ID: <001601c70f9d$9040dac0$03000080@hendrik> "Tim Roberts" wrote: > "Hendrik van Rooyen" wrote: > > >"flamesrock" wrote: > > > >8<---------------------------------- > > > >> .... since the statement itself > >> occurs at one time instant.. > > > >nothing, but nothing, can occur at one time instant.... > > Well, as long as we're being pedantic, surely that should read "only one > thing can occur at any time instant..." No its worse than that - what I mean is that everything takes finite time... :-) Hendrik From martin.witte at gmail.com Thu Nov 16 03:27:09 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 16 Nov 2006 00:27:09 -0800 Subject: More puzzling behavior while subclassing datetime In-Reply-To: <1163659104.321150.322650@e3g2000cwe.googlegroups.com> References: <1163659104.321150.322650@e3g2000cwe.googlegroups.com> Message-ID: <1163665629.726810.228120@m7g2000cwm.googlegroups.com> insyte at gmail.com wrote: > With assistance from Gabriel and Frederik (and a few old threads in > c.l.p.) I've been making headway on my specialized datetime class. Now > I'm puzzled by behavior I didn't expect while attempting to use some of > the alternate datetime constructors. Specifically, it appears if I > call GeneralizedTime.now() it calls the __new__ method of my class but > treats keyword arguments as if they were positional. > > My class: > > class GeneralizedTime(datetime): > def __new__(cls, time=None, *args, **kwargs): datetime.datetime() takes these arguments: year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]), see http://docs.python.org/lib/datetime-datetime.html > print time, args, kwargs > if isinstance(time, str): > timeValues, tzOffset = cls.stringToTimeTuple(time) > return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset), > **timeValues) > elif isinstance(time, datetime): > timeValues = time.timetuple()[:6] time.timetuple() does not exist, see http://docs.python.org/lib/module-time.html, time is represented as a tuple. checkout time.mktime() on how to convert to a tuple to a time > tzOffset = time.utcoffset() > return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset), > *timeValues) > elif time is None: > print "Still gotta figure out now to do this one..." > else: > raise Invalidtime(time) > @staticmethod > def stringToTimeTuple(timeString): > ... regex that parses timeString ... > > >>> GeneralizedTime.today() > 2006 (11, 16, 0, 35, 18, 747275, None) {} > Traceback (most recent call last): > File "", line 1, in ? > File "gentime.py", line 106, in __new__ > raise InvalidTime(time) > gentime.InvalidTime: 2006 > > So it appears the time tuple is being passed to > GeneralizedTime.__new__, but the first value is being assigned to the > "time" argument. > > Is this a side effect of how datetime is implemented? Or am I doing > something screwy? > > Thanks! > > -Ben A very cutback part of your code gets the basics working: from datetime import datetime class Invalidtime(Exception): pass class GeneralizedTime(datetime): def __new__(cls, *args, **kwargs): if isinstance(args, tuple): return datetime.__new__(cls, *args) else: raise Invalidtime(args) t = GeneralizedTime.today() print t.year print t.month print t.day print t.hour print t.minute print t.second print t.microsecond print t.tzinfo From apardon at forel.vub.ac.be Wed Nov 15 03:22:46 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 15 Nov 2006 08:22:46 GMT Subject: Py3K idea: why not drop the colon? References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <45535475.9090207@hobbshouse.org> <87ac30kwdn.fsf@benfinney.id.au> <4554AAB4.10002@hobbshouse.org> <17750.22816.636590.485360@montanaro.dyndns.org> <4558B9E3.2040207@hobbshouse.org> Message-ID: On 2006-11-15, Steven D'Aprano wrote: > On Tue, 14 Nov 2006 12:01:05 +0000, Antoon Pardon wrote: > >> On 2006-11-13, Ben Finney wrote: >>> Michael Hobbs writes: >>> >>>> To be clear, this is the actual thrust of my argument. It seems >>>> redundant to have *both* line continuations and colons in compound >>>> statements. >>> >>> Why are you trying to remove redundancy? >> >> Why not? My impression is that removing redundancy is considered >> a positive thing here in c.p.l. > > Redundancy in *what*? Redundancy in whatever proposal the opponent doesn't like. > Redundancy is not something to be valued for its own sake. It is only > valuable when it actually gains you something. In the same way it is not something to be eliminated for its own sake. But if someone doesn't like a particulare proposal and the proposal happens to introduce some redundancy then there is a reasonable chance the proposal will be dismissed by simply observing that it introduces redundancy. > The question is not "is the colon redundant?" but "is the colon useful > despite, or even because, its redundancy?". There are two schools of > thought: > > (1) Yes, it is useful, *because* of its redundancy -- it helps the human > reader parse and comprehend the source code. > Evidence given: usability studies by the ABC project. I wonder, did this project also studied the readability of: if a == b then > (2) No, it is not useful, because the computer parser doesn't need it. > Evidence given: "it seems to me" repeated loudly until our ears bleed. A pity that no such study seems to exists concerning code that uses only indentation to mark structure and code that uses indentation and some kind of delimiter for showing the boundaries of (sub) structures. Because the evidence for end markers not being usefull seems to fall in the same category as (2) here above. -- Antoon Pardon From siona at chiark.greenend.org.uk Thu Nov 16 11:14:46 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 Nov 2006 16:14:46 +0000 (GMT) Subject: ini files and plugins References: <455c7d58$0$21668$426a74cc@news.free.fr> Message-ID: <2lj*DoYvr@news.chiark.greenend.org.uk> tool69 wrote: >I've made a basic LaTeX file editor in wxPython, but now I wanted to add >it some features : ^^^^^^^^ >1 - create a sort of ini file where I can put the user configuration >that will load itself on the application startup ; wx.Config? (If it absolutely has to be a .ini file on Windows, not the registry, you can force that if you want.) -- \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" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From ptmcg at austin.rr._bogus_.com Sun Nov 19 16:29:59 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 19 Nov 2006 21:29:59 GMT Subject: Programmatically finding "significant" data points References: <1163513101.580610.151420@b28g2000cwb.googlegroups.com> Message-ID: ... dang touchy keyboard! > Here is some sample data: > data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, > 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, > 0.10] > > In this data, some of the significant points include: > data[0] > data[2] > data[4] > data[6] > data[8] > data[9] > data[13] > data[14] Using the first derivative, and looking for sign changes, finds many of the values you marked as "significant". -- Paul data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, 0.10] delta = lambda (x1,x2) : x2-x1 dy_dx =[0]+map(delta,zip(data,data[1:])) d2y_dx2 = [0]+map(delta,zip(dy_dx,dy_dx[1:])) sgnChange = lambda (x1,x2) : x1*x2<0 sigs = map(sgnChange,zip(dy_dx,dy_dx[1:])) print [i for i,v in enumerate(sigs) if v] [2, 4, 6, 8, 9, 10, 13, 14, 15, 17, 18, 19, 20] From steve at REMOVE.THIS.cybersource.com.au Sat Nov 25 16:28:19 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 26 Nov 2006 08:28:19 +1100 Subject: The Python Papers Edition One References: <1164080670.604928.113480@m73g2000cwd.googlegroups.com> <1164106267.882164.124670@h48g2000cwc.googlegroups.com> <1164156093.359433.315790@e3g2000cwe.googlegroups.com> <1164471238.033790.243890@14g2000cws.googlegroups.com> Message-ID: On Sat, 25 Nov 2006 08:13:58 -0800, Noah Slater wrote: > > On Nov 22, 12:41 am, "tleeuwenb... at gmail.com" > wrote: >> Thanks for the comments. PDF is, to some extent, a requirement. To >> preserve the entire journal as a single "entity" with a reasonably high >> production quality, there seems to be no way around it. I could not >> find a sufficiently simple way to do multi-format publishing with an >> attractive layout and good typesetting. > > Which is more important to the Python comunity... > > Good typesetting or good, searchable, copyable, usable information? Such a sweeping generalization, as if "the Python community" only wanted one thing. In any case: (1) Whether the Python Papers is "good" depends on what content it includes, not the file format it is published in. (2) Google can index PDF files. If the Python Papers aren't reachable by Google's spiders, well, I consider that the Kiss of Death for them. (3) Code in the Python Papers are certainly legally copyable, and if your PDF viewer doesn't let you copy text from PDFs, use another PDF viewer: [quote from page 4 of the Python Papers] def process(self): ''' Processes the payment into the financial system ''' self._recordPayment() self._despatchOrder() self._sendConfirmation() self._concludePayment() def _recordPayment(): ''' Make a permanent record of the payment in the database ''' pass Works fine for me, although I would question the choice of TWO spaces for indents. (4) The Python Papers are certainly legally usable, for non-commercial use. For commercial use, you have at least two legal options: - treat the work the same as you would any piece of code with an unacceptable licence, and develop your own NON-derivative version. It's only copyrighted, not patented: you are still allowed to write your own independent version. Merely having read a work doesn't necessarily contaminate whatever you write next. - contact the author of the work and ask for a commercial licence. You may have to pay a licence fee, or perhaps not. Instead of bitching and moaning about it, how about you submit your own work to the Python Papers under a dual licence? It can be both CC Non-commercial, and GPL (or whatever licence you like). I assume the purpose of the Non-commercial licence is to prevent somebody taking up the Python Papers in full and charging for it. (Personally, I think that is a very low risk -- who cares if somebody tries to charge for it? They can't compete with the gratis version being given away for nothing.) Dual licences for the contributed articles will still protect the over-all integrity of the magazine from being sold for profit, while still allowing coders to duplicate useful code and use it in whatever they choose. That way, the Python Papers themselves continue to be free as in beer, and individual articles can, according to their authors wishes, be *at least* gratis and possibly free as in speech as well. -- Steven. From johnjsal at NOSPAMgmail.com Mon Nov 13 13:07:28 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 13 Nov 2006 13:07:28 -0500 Subject: Py3K idea: why not drop the colon? In-Reply-To: References: <1163011098.177396.39360@m7g2000cwm.googlegroups.com> <455226c0$0$17087$c3e8da3@news.astraweb.com> <45530513$0$25102$426a74cc@news.free.fr> <1163089657.164900.112820@f16g2000cwb.googlegroups.com> <45538b0d$0$26485$c3e8da3@news.astraweb.com> Message-ID: <4558b437$0$32430$c3e8da3@news.astraweb.com> Fredrik Lundh wrote: > John Salerno wrote: > >>> Anyway, the FAQ answer seems to be a weak argument to me. >> >> I agree. I was expecting something more technical to justify the >> colon, not just that it looks better. > > yeah, the whole idea of treating programming languages as an interface > between people and computers is really lame. no wonder nobody's using > Python for anything. > > > personally, i don't mind the colon and see no need to lose it, but if we are talking in the realm of aesthetics, it actually seems like it would be cleaner if it weren't there...sure, at first everyone who is used to it might feel like something is missing, or the line is "hanging" open, but overall the less characters, the better, right? isn't that why the braces are gone? From mail at microcorp.co.za Wed Nov 22 01:56:48 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 22 Nov 2006 08:56:48 +0200 Subject: Is time.time() < time.time() always true? References: <1164150625.377064.112550@j44g2000cwa.googlegroups.com> Message-ID: <015d01c70e05$f7564540$03000080@hendrik> "flamesrock" wrote: 8<---------------------------------- > .... since the statement itself > occurs at one time instant.. nothing, but nothing, can occur at one time instant.... - Hendrik